0

Hi i am writing a code where, i have to switch a variable called toggle from 0 to 1 to 0.... every time the button is pressed (the button is on a 2 pin). I am a little lost as I am new to arduino need some help. Thank you

0

2 Answers 2

2

Go here --> Built-In Examples. Read the examples for Button, Debounce, and Digital Input Pullup. Digital Input Pullup is the best single one of those 3 I think, but read them all.

Those 3 are key.

Also, I wrote a buttonReader (debouncing) library here.

Sounds like you're a beginner, so check out Adafruit's tutorials here.

And lastly, I've compiled links to all my knowledge at the bottom of my article here.

1
  • 2
    You might want to make your answer a little bit more substantive than simply including links to sites that may or may not exist by the time someone else looks at the question.
    – ILMostro_7
    Oct 22, 2015 at 1:06
2

What you need is to detect a transition. That is, either:

  • It was closed and is now open.

Or:

  • It was open and is now closed.

To do that you need to "remember" the previous state of the switch and detect a change, like this:

const byte switchPin = 8;
byte oldSwitchState = HIGH;  // assume switch open because of pull-up resistor
bool toggle;

void setup ()
  {
  pinMode (switchPin, INPUT_PULLUP);
  }  // end of setup

void loop ()
  {
  // see if switch is open or closed
  byte switchState = digitalRead (switchPin);

  // has it changed since last time?
  if (switchState != oldSwitchState)
    {
    oldSwitchState =  switchState;  // remember for next time 
    toggle = !toggle;   // toggle the variable
    delay (10);         // debounce
    }  // end of state change

  // other code here ...

  }  // end of loop

For more information see my post about switches.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.