const int BUTTON_PIN = 7; // Arduino pin connected to button's pin
const int LED_PIN = 2; // Arduino pin connected to LED's pin
// variables will change:
boolean ledState = false; // the current state of LED
boolean lastButtonState = false; // the previous state of button
boolean currentButtonState = false; // the current state of button
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() {
lastButtonState = currentButtonState; // save the last state
currentButtonState = digitalRead(BUTTON_PIN); // read new state
if(lastButtonState == HIGH && currentButtonState == LOW) {
Serial.println("The button is pressed");
// toggle state of LED
ledState = !ledState;
// control LED arccoding to the toggled state
if (ledState == true){
digitalWrite(LED_PIN, HIGH);
}
if (ledState == false){
digitalWrite(LED_PIN, LOW);
}
delay(500);
}
}