Yale High School Physics
Tuesday, September 9, 2014
A Toggle Button
Copy and past the code below the line of asterisks:
**********************************************
// Working on a Toggle Switch // // September 10, 2014 // int mode = 0; // a variable to store whether it's "on" or "off" int oldMode = 0; // stores the previous mode int buttonState = HIGH; // a variable to tell whetehr or not the button is depressed int oldButtonState = HIGH; // stores the previous state int buttonPin = 5; // your's may be different void setup() { pinMode(buttonPin,INPUT_PULLUP); Serial.begin(9600); } void loop() { buttonState = digitalRead(buttonPin); // reads in whether or not the button is depressed if(buttonState == LOW && oldButtonState == HIGH) // is this is newly pressed button? { // the code that's inclosed here in these braces only is executed when it's a new button press if(oldMode == 0) { Serial.println("on"); // print "on" mode = 1; // sets the new mode to "on" } if(oldMode == 1) { Serial.println("off"); //print "off" mode = 0; // sets the new mode back to "off" } oldMode = mode; // updates the oldMode so that it is current } delay(50); // pause 50 milliseconds to "debounce" the button to avoid accidental double-presses oldButtonState = buttonState; // updates the old state so that it is current }
No comments:
Post a Comment
Newer Post
Older Post
Home
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment