/* ELECTRO SCHEMATICS, Turn ON an LED with a Button and Arduino – Tutorial #4, sketch 3 Turn on a LED when the button is pressed and let it on until the button is pressed again Blink the LED when the button is hold Modified by Kati Pitkänen 19.5.2018 */ const int pinButton = 7; // The number of the pushbutton pin const int pinLED = 8; // The number of the LED pin int stateLED = LOW; int stateButton; // Variable for reading the pushbutton status int previousStateButton = HIGH; long time = 0; long debounce = 25; // Debounce an input by checking twice in 25ms to make sure the button is really pressed int buttonHold; void setup() { pinMode(pinButton, INPUT); // Set the pushbutton pin as an INPUT pinMode(pinLED, OUTPUT); // Set the LED pin as an OUTPUT } void loop() { stateButton = digitalRead(pinButton); // Read the state of the button // check if the button is pressed -- if it is, the buttonState is LOW [because the button has a PULL-UP resistor] // Detect the current mode and set the LED appropriately: if(stateButton == LOW && previousStateButton == HIGH && millis() - time > debounce) { if(stateLED == HIGH){ stateLED = LOW; } else { stateLED = HIGH; } time = millis(); // Millis() function keeps track of the time passed since the button was pressed } digitalWrite(pinLED, stateLED); // Set pinLED HIGH or LOW with the stateLED of the variable previousStateButton == stateButton; if(buttonHold) { if(stateButton == LOW) { digitalWrite(pinLED, HIGH); // Turn the LED ON delay(25); // Wait for 25 milliseconds digitalWrite(pinLED, LOW); // Turn the LED OFF delay(25); // Wait for 25 milliseconds } else { digitalWrite(pinLED, LOW); // Turn the LED OFF } } }