// Button Example Two (active low)
//
// Button not pressed: signal is HIGH
// Button pressed : signal is LOW
//
// The resistor keeps pin 4 high when the button
// is not pressed.
// The resistor is a pullup resistor.
//
// Button Example One: https://wokwi.com/projects/397990618860958721
// Button Example Two: https://wokwi.com/projects/397990611031240705
//
// The external resistor is optional, since
// also the internal pullup resistor is turned on.
//
// 16 May 2024, by Koepel, Public Domain.
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);
}
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 == LOW)
{
Serial.println("The button is pressed.");
}
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);
}