Digital Input Pullup example script (arduino.py) Reads a pushbutton on D2 using the pin's pull-up resistor, so no other parts are needed, prints its state and lights the on-board LED while it is pressed.
- Wiring
- A pushbutton between D2 and GND. The pull-up holds D2 at 1 while the button is open, so the logic is inverted: pressed reads 0.
from arduino import *
BUTTON_PIN = 2
def setup():
pinMode(BUTTON_PIN, INPUT_PULLUP)
pinMode(LED_BUILTIN, OUTPUT)
def loop():
state = digitalRead(BUTTON_PIN)
print(state)
if state == LOW:
digitalWrite(LED_BUILTIN, HIGH)
else:
digitalWrite(LED_BUILTIN, LOW)
delay(100)
def main():
setup()
while True:
loop()
if __name__ == "__main__":
main()