Catch a button press
For this part of the example, you write code that responds to a button press on the XBIB-CU-TH-DEV board that comes with the XBee Smart Modem Development Kit. The code monitors the pin connected to the button on the board labeled Comm.
On the board you see DIO0 written below Comm, to the left of the button. This represents the pin that the button is connected to.
In MicroPython, you will create a pin object for the pin that is connected to the Comm button. When you create the pin object, the DIO0 pin is called D0 for short.
The loop continuously checks the value on that pin and once it goes to 0 (meaning the button has been pressed) a print() call prints the message Button pressed! to the screen.
At the MicroPython >>> prompt, copy the following code and enter it into MicroPython using paste mode (Ctrl+E), right-click in the Terminal, select Paste to paste the copied code, and press Ctrl+D to run the code.
# Import the Pin module from machine, for simpler syntax.
from machine import Pin
# Create a pin object for the pin that the button "DIO0" is connected to.
dio0 = Pin("D0", Pin.IN, Pin.PULL_UP)
# Give feedback to inform user a button press is needed.
print("Waiting for DIO0 press...")
# Create a WHILE loop that checks for a button press.
while (True):
if (dio0.value() == 0): # Once pressed.
print("Button pressed!") # Print message once pressed.
break # Exit the WHILE loop.
# When you press DIO0, you should see "Button pressed!" printed to the screen.
# You have successfully performed an action in response to a button press!
Note You can easily copy and paste code from the online version of this guide. Use caution with the PDF version, as it may not maintain essential indentations.
Note If you have problems pasting the code, see Syntax error at line 1.