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

asked Sep 29, 2015 at 17:25
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.

answered Sep 29, 2015 at 17:40
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. Commented 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.

answered Sep 29, 2015 at 21:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.