I'm experiencing a strange delay with my push button sketch

Hello All,

Newbie question:

I put a push button on pin7 and shorting it to 5v when pressed, on an Uno R3 - with the following sketch:

int ledPin = 13; // choose the pin for the LED
int inPin = 7;   // choose the input pin (for a pushbutton)
int val = 0;     // variable for reading the pin status

void setup() {
  pinMode(ledPin, OUTPUT);  // declare LED as output
  pinMode(inPin, INPUT);    // declare pushbutton as input
  Serial.begin(9600);      // start the Serial monitor 
}

void loop(){
  val = digitalRead(inPin);  // read input value


  if (val == LOW) {         // check if the input is HIGH (button released)
    Serial.println("Low");       // debug xCount
  } else if (val == HIGH) {
    Serial.println("Hi");       // debug xCount
  }
  
    // delay(250);                 // slow it down for debug
}

The thing is, pin7 is NOT stablized on low. On the serial monitor, I get readings like this:

Low
Low
Hi
Low
Low
Hi
Hi
Low
Low
Hi
Low
Low
Hi
Hi
Low
Low
Hi
...

Why is this happening? Shouldn’t pin7 read a stable low?

Also, when I let go of the button, it takes between 500ms to a full second before the pin goes back to low. As a result, I get many more “High” readings on the Serial Monitor.

Finally, I should also mention that adding that delay of 250ms did not really help either (so I commented it out).

Please advise.

Thank you,
/F

Do you have a R to gnd from the switch input? 10k is good.

Weedpharma

^ That.

Or use the internal pullup resistor.

Change: pinMode(inPin, INPUT); to: pinMode(inPin, INPUT_PULLUP);

Connect your button between input pin and ground.

All logic is reversed now, so... Change all HIGHs and LOWs accordingly. Leo..

Thanks much guys. Worked like a charm :-)