The button is almost always on HIGH

There is a simple code to write to the Serial if the button is pressed or not.

void setup() {
  Serial.begin(9600);
  pinMode(7, INPUT);
}

void loop() {
  delay(500);
  if (digitalRead(7) == HIGH) {
    Serial.println("On");
  } else if (digitalRead(7) == LOW) {
    Serial.println("Off");
  }
}

But in Serial is always ON, and usualy, when i only touch, is OFF

how did you wire the button? do you have an external pullup or pulldown resistor?

try wiring pin 7 --- button ---- GND and use

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

void loop() {
 delay(500);
 if (digitalRead(7) == HIGH) {
   Serial.println("On");
 } else {
   Serial.println("Off");
 }
}

mind bouncing (when you get rid of the delay)

I have this button: PS10C

i have it connnected on Pin 7 and 5V, i am beginner.

Hello tom_25

Take this picture as basic information to continue:

Please read something about using pin's pullup and pulldown.
With your connection the potential on the pin 7 will be free floating when the switch is off, so the digitalRead() can returns any value, depend on electromagnetic noise.

we all have been beginners. so if you've done this

what happens when the button is not pressed is that the green wire behaves like an antenna connected to your pin 7 and you read whatever electromagnetic field is in the air because there is nothing forcing pin 7 to GND.

read about pull-up and pull-down resistors (first google hit https://eepower.com/resistor-guide/resistor-applications/pull-up-resistor-pull-down-resistor/# )

if you use INPUT_PULLUP instead of INPUT for your pin, then you force the signal HIGH internally in the microcontroller so if you connect the other end to GND then you'll read HIGH when not pressed and LOW when pressed. see https://www.arduino.cc/en/Tutorial/BuiltInExamples/InputPullupSerial

ok, but when i pressed, why it is OFF? And when it´s not pressed, why it is on?

Well, never mind, thank you very much.

Probably because this button is normally closed and opens when pressed

I guess you figured it out :slight_smile:

1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.