/* MultipleLEDsPushButton Cycle through three LEDs with a pushnutton */ const int pushButtonPin = 2; // connect the push button to digital pin 2 const int led0 = 13; // connect an LED to pin 13 const int led1 = 12; // connect an LED to pin 12 const int led2 = 11; // connect an LED to pin 11 const int debounceTime = 5; // number of millisecods to delay after button press int ledState; // used to decide which LED is on (0 to 2) boolean lastButtonState = HIGH; // value of buttonState from previous loop iteration boolean buttonState = HIGH; // start by assuming button is unpressed boolean debounce(int pinNum) { delay(debounceTime); return digitalRead(pinNum); } void setup() { pinMode(pushButtonPin, INPUT); // make the pushbutton's pin an input digitalWrite(pushButtonPin, HIGH); // turn on pullup resistors // make LED pins outputs pinMode(led0, OUTPUT); pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); // initialize state ledState = 0; // turn the correct LED on and the others off digitalWrite(led0, HIGH); digitalWrite(led1, LOW); digitalWrite(led2, LOW); } void loop() { buttonState = debounce(pushButtonPin); // read the input pin // if button goes down and previously it was high... if (buttonState == LOW && lastButtonState == HIGH) { ledState = (ledState + 1) % 3; // cycle through 0,1,2 } // turn the correct LED on and the others off if (ledState == 0) { digitalWrite(led0, HIGH); digitalWrite(led1, LOW); digitalWrite(led2, LOW); } else if (ledState == 1) { digitalWrite(led0, LOW); digitalWrite(led1, HIGH); digitalWrite(led2, LOW); } else if (ledState == 2) { digitalWrite(led0, LOW); digitalWrite(led1, LOW); digitalWrite(led2, HIGH); } else // turn all LEDs on to indicate an error state. { digitalWrite(led0, HIGH); digitalWrite(led1, HIGH); digitalWrite(led2, HIGH); } lastButtonState = buttonState; }