const int buttonPin = 8;
int oldValue = LOW; // default/idle value for pin 8 is low.
void setup() {
Serial.begin(115200);
Serial.println("Press the button to turn on the light.");
// Initialize the pin for reading the button.
pinMode(buttonPin, INPUT);
pinMode(LED_BUILTIN, OUTPUT); // Set LED pin as output
}
void loop() {
// Read the value of pin 8.
int newValue = digitalRead(buttonPin);
// Check if the value was changed,
// by comparing it with the previous value.
if(newValue != oldValue)
{
if(newValue == HIGH)
{
//Serial.println("Light on.");
digitalWrite(LED_BUILTIN, HIGH); // turn the LED on (HIGH is the voltage level)
}
else
{
//Serial.println("Light off.");
digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
}
// Remember the value for the next time.
oldValue = newValue;
}
// Slow down the sketch.
// Also for debouncing the button.
delay(100);
}