State Change Detection example script (arduino.py) Counts presses of a pushbutton on D2 and lights the on-board LED on every fourth press. It acts on the change from released to pressed (an edge), not on the button being held down.
- Wiring
- A pushbutton between D2 and 3.3 V; the pull-down holds D2 at 0 while the button is open.
- Output
on
number of button pushes: 1
off
from arduino import *
BUTTON_PIN = 2
presses = 0
last_state = LOW
def setup():
pinMode(BUTTON_PIN, INPUT_PULLDOWN)
pinMode(LED_BUILTIN, OUTPUT)
def loop():
global presses, last_state
state = digitalRead(BUTTON_PIN)
if state != last_state:
if state == HIGH:
presses += 1
print("on")
print("number of button pushes:", presses)
else:
print("off")
delay(50)
last_state = state
if presses % 4 == 0:
digitalWrite(LED_BUILTIN, HIGH)
else:
digitalWrite(LED_BUILTIN, LOW)
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()