// Using a momentary switch to alternate behavior // each time it is pressed // Variables int mySwitch = 0; int switchPin = 8; // Variables to track toggling of the switch int whichToggle = 1; int toggleFlag = 1; // Setup void setup() { Serial.begin(9600); pinMode(switchPin, INPUT); } // Das loop... void loop() { // Look for the switch's status in every cycle of the loop. // Note that the switch is set to be normally HIGH mySwitch = digitalRead(switchPin); // Toggling a switch presents a problem. If you hold down the switch, // it will toggle back and forth while it's held down unless you // use another variable (toggleFlag) to track whether or not the switch // has been released, and use that variable to keep the toggle from // occuring while the switch is held down. if(!mySwitch) { // Check if the switch is pressed if (toggleFlag) { // Check if toggleFlag is true. whichToggle = !whichToggle; // If it is, then toggle whichToggle toggleFlag = 0; // and turn toggleFlag off. } }else{ toggleFlag = 1; // Reset toggleFlag when the switch } // is released. Serial.println(whichToggle); }