// constants won't change
const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int LED_PIN = 3; // Arduino pin connected to LED's pin
// variables will change:
bool ledState = false; // variable to hold LED state
int lastButtonState = HIGH; // pullup pin idles HIGH
void setup() {
Serial.begin(9600); // initialize serial
pinMode(BUTTON_PIN, INPUT_PULLUP); // set arduino pin to input pull-up mode
pinMode(LED_PIN, OUTPUT); // set arduino pin to output mode
}
void loop() {
int currentButtonState = digitalRead(BUTTON_PIN); // read the button
if (lastButtonState != currentButtonState) { // if it changed
lastButtonState = currentButtonState; // save the state
if (currentButtonState == LOW) { // if LOW was just pressed
Serial.println("The button was just pressed");
// toggle state of LED
ledState = !ledState;
// control LED arccoding to the toggled state
digitalWrite(LED_PIN, ledState);
} else { // if HIGH was just released
Serial.println("The button was just released");
}
delay(20); // debounce the button
}
}