How does a button work?

Hi, I have a simple sketch where I have an audible tone constantly coming out of PIN 3, and LED is blinking on PIN 13. I also have an AND gate that takes both PIN 3 and PIN 13 as input to produce sound only when the LED is on. Now I put a button between the LED and the AND gate. I expect the button to act as a simple switch - pressed there is signal, released there is no signal. But in this emulator sketch ButtonIssue - wokwi even when the LED is not ON there is still a signal if you press the button a few times. Can someone please explain why there is a signal if the LED is off and how to make it work as expected? Tha nk you!

#define BUZZER_PIN 3

long _ms;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode(BUZZER_PIN, OUTPUT);
  
  _ms = millis();
}


void loop() {
  digitalWrite(BUZZER_PIN, HIGH);
  delay(1);
  digitalWrite(BUZZER_PIN, LOW);
  delay(1);

  if (millis() - _ms > 3000) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    _ms = millis();
  }
}

The bottom input of the AND gate is floating whenever the button is not pressed, you need a pull-down resistor.
Also, why connect the button after the LED series resistor rather than directly to the Arduino pin?

How do I connect it? Is it just a resistor between the button and the AND gate? That did not work in the emulator...

I am a beginner at this, I connected it directly now. Thank you for you response!

No, the button remains connected to the AND gate directly. The resistor goes between the AND gate input and ground, so the voltage on the input is at 0v whenever the switch is open.

Thank you, I think that did the trick. I don't fully understand how a pullup/down resistor works. I understand that it prevents floating voltage, but the physics of it is unclear to me still.... Somehow the current chooses to go to the ground if there's a pulldown resistor? Magic.. :slight_smile: Thanks again!

You can simply apply Ohm's law and Kirchhoff's laws for both cases (button pressed or released). Use the fact that no current flows into the input of an ideal AND gate.

2 Likes

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