DigitalRead does not return true values

So, I have written this sketch

void setup(){
    pinMode(7, INPUT_PULLUP);
    Serial.begin(250000);
}

void loop(){
     int val=digitalRead(7);
     Serial.println(val);
     delay(2);
}

I have wired the switch like GND->switch->pin 7
When the switch is off, digitalRead will for sometime return 1(as expected) and then randomly return a one or two zeroes.
The same thing goes when the switch is on. It returns zeroes(as expected) and then a one or two ones.

Learn about switch bounce. Mechanical switches do not switch cleanly which is why they need debouncing.

I thought of that, and I tried changing the mechanical switch with an optocoupler. The result is the same. I don't know if the problem is because of the big 3-phase transformer nearby.

When the switch is off, digitalRead will for sometime return 1(as expected) and then randomly return a one or two zeroes.

Sounds like dodgy wiring to me. Take the switch and associated wiring out of the circuit leaving a bare Arduino board. What do you see when you run the program ?

UKHeliBob:
Sounds like dodgy wiring to me. Take the switch and associated wiring out of the circuit leaving a bare Arduino board. What do you see when you run the program ?

For sometime returns 1, and at some point return one or two zeroes, then ones again? This behavior is very strange to me.

With nothing, not even a wire connected to pin7 you occasionally get a reading of 0?

In that case nearby transformer or unstable power supply is very likely the cause of the problem.

Gabriel_swe:
With nothing, not even a wire connected to pin7 you occasionally get a reading of 0?

In that case nearby transformer or unstable power supply is very likely the cause of the problem.

Thanks, I will look into that.

braev:
So, I have written this sketch

void setup(){

pinMode(7, INPUT_PULLUP);
   Serial.begin(250000);
}

void loop(){
    int val=digitalRead(7);
    Serial.println(val);
    delay(2);
}

Serial baud rate of 250000 will push the Arduino to its limits.

Did you try also a lower baud rate of 9600 or 115200 maybe? Does the baud rate make a difference in your observations?

Try a 4k7 pullup on pin 7.

756E6C:
Try a 4k7 pullup on pin 7.

Why, when the pin is already being pulled HIGH ?

UKHeliBob:
Why, when the pin is already being pulled HIGH ?

4k7 is a considerably stronger pullup than the built-in 50k or so