Pushbutton Values Spazzing Out (Very Easy)

I was creating a simple safecracking puzzle that involved finding a specific value on a potentiometer, then pressing a button to lock it in. I created it using an emulator, where it worked perfectly fine. However, when creating it IRL the pushbutton values were spazzing out, flickering between 0 and 1 when the button was unpressed. I was very simply wiring it with a 5v wire going into 1a and another wire coming out of 2b going into pin 12.

TL;DR: Pushbutton spazzing between 1 and 0 when unpressed.

Code (cut down to just the button parts):


void setup()
{
  pinMode(12, INPUT);
  Serial.begin(9600);
}
void loop()
{
  int button = digitalRead(12); //sets button to pin 12
  Serial.println(button); //for debugging

  if (button == 1){ // sets button to 1000 if its 1 ,for a different part of my code that I cut
  button = 1000;
  }else{
    button = 0;
  } 
}

Did you mean Pin 11? Since you aren't using pinMode(11, INPUT_PULLUP); you MUST use an external pull-up or pull-down resistor. Which is it?

Sorry, total mistake. I meant to write 12 in all those 11's. I'm not quite sure what you mean by pull-up and pull-down resistors.

Edit: edited the code in the original post

To keep an input pin from 'floating' (or 'spazzing out') you have to connect it through a resistor to +5V or Gnd. The internal hardware has a pull-up (+5V) resistor you can enable. If you don't enable that, you must provide your own external resistor.

For a button, the easiest way is to use INPUT_PULLUP mode and connect your button between the pin and Ground. When the button is open, the pull-up resistor causes the pin to read HIGH. When you the button is closed (connecting the pin to Ground) the pin reads LOW.

Many Arduino tutorials use an external pull-down resistor between the input pin and Ground. The button then goes between the pin anf +5V. When the button is open the pull-down causes the pin to read LOW. When the button is closed, the 5V line cine causes the pin to read HIGH.

So, (if I read this correctly,) If I change it to pinMode(12, INPUT_PULLUP), it should work where when the button isn't pressed, it's low, and when it is, it's high?

Push/closed = LOW

image

No. If you use the internal pullup you need to change the wiring, too. You will wire the switch one side to ground and one side to the input with its pinMode set to INPUT_PULLUP (the accepted way) the input will read HIGH when not pressed and LOW when pressed.

Thank you guys, I'll try this out when I get the time but it looks as if it will work!

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