%{ title: "Monitor a Normally-Open Pushbutton", description: "Control an LED with a normally-open pushbutton connected to a GPIO pin.", topics: ["gpio"], level: "Beginner" } --- ## Overview Monitoring and responding to user input is a fundamental skill. This epxeriment will demonstrate program control with a normally-open pushbutton. In this experiment the button is connected to ground; this is known as an "active-low" input as the GPIO pin will see 0 when the button is pressed, and 1 when the button is released (to the internal pull-up). ## Schematic Connect a 1K resistor and a nomrally-open pushbutton between **P1** and **GND** as shown. The 1K resistor will protect the GPIO pin if it is accidentally made an output and high while the button is pressed. ``` P1 ----[ 1K ]----[N.O. BTN]---- GND P0 ----[220R]----[+ LED -]----- GND ``` ## SPIN2 Code ```spin CON _clkfreq = 200_000_000 BTN_PIN = 1 LED_PIN = 0 PUB main() | bstate pinlow(LED_PIN) ' star with LED off wrpin(BTN_PIN, P_HIGH_15K) ' add pull-up to button pin pinhigh(BTN_PIN) ' activate pull-up repeat bstate := pinread(BTN_PIN) ' get state of button if (bstate == 0) ' if pressed pinhigh(LED_PIN) ' turn the LED on else ' else pinlow(LED_PIN) ' turn the LED off ## SPIN2 Code (Refined) This version introduces the pinwrite() function to update the LED with the state of the button input. As button is configured as active-low, the program XORs (^) the input with 1 to invert the input state to match the LED. ```spin CON _clkfreq = 200_000_000 BTN_PIN = 1 LED_PIN = 0 PUB main() pinlow(LED_PIN) ' star with LED off wrpin(BTN_PIN, P_HIGH_15K) ' add pull-up to button pin pinhigh(BTN_PIN) ' activate pull-up repeat ' copy inverted state of button to LED pinwrite(LED_PIN, pinread(BTN_PIN) ^ 1) ## SPIN2 Code (Refined, Version 2) This version demonstrates how the input state of a button input can be inverted with configuration, allowing the value read from the pin to be used directly. ```spin CON _clkfreq = 200_000_000 BTN_PIN = 1 LED_PIN = 0 PUB main() pinlow(LED_PIN) ' star with LED off wrpin(BTN_PIN, P_HIGH_15K | P_INVERT_IN) ' add pull-up to button pin, invert input state pinhigh(BTN_PIN) ' activate pull-up repeat ' copy state of button to LED pinwrite(LED_PIN, pinread(BTN_PIN))