const int buttonPin = 4;
int oldValue = HIGH; // default/idle value for pin 4 is high.
void setup()
{
Serial.begin(115200);
Serial.println("Press the button.");
// Initialize the pin for reading the button.
pinMode(buttonPin, INPUT_PULLUP);
pinMode(2, OUTPUT);
}
void loop()
{
// Read the value of pin 4.
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("The button is pressed.");
digitalWrite(2, HIGH);
}
else
{
Serial.println("The button is released.");
}
// Remember the value for the next time.
oldValue = newValue;
}
// Slow down the sketch.
// Also for debouncing the button.
delay(100);
}