// ------ Reads the state of a switch and lights LEDs accordingly ---
// -Using variables to store pin numbers
//
// > Wire an LED from Pin 7 thru 330 ohm resistor to GND
// > Wire an LED from Pin 6 thru 330 ohm resistor to GND
// > Wire a switch between Digital Pin 5 and GND
//---------------------------------------------------------------------
boolean buttonState = 0; // create variable for storing "state" of the button
int LED1 = 7; // create variable for LED pin number
int LED2 = 6; // create variable for LED pin number
int buttonPin = 5; // create variable for button pin number
void setup() { // Only do once at startup
pinMode(LED1, OUTPUT); // initialize digital pin as an output (for LED1.)
pinMode(LED2, OUTPUT); // initialize digital pin as an output (for LED2.)
pinMode(buttonPin, INPUT_PULLUP); // initialize digital pin as an input (for switch.)
}
void loop() { // repeat forever
buttonState = digitalRead(buttonPin); // "Read" the voltage present on the pin (check switch.)
//-- If the pin wired to the button is low, the switch is closed
if (buttonState == LOW) {
digitalWrite(LED2, LOW); // turn LED2 off:
digitalWrite(LED1, HIGH); // blink LED1
delay(75);
digitalWrite(LED1, LOW);
delay(75);
}
// Otherwise, assume the switch is open.
else {
digitalWrite(LED2, HIGH); // turn LED2 on:
digitalWrite(LED1, LOW); // turn LED off:
}
}
|