CircuitPython Digital In & Out

The first part of interfacing with hardware is being able to manage digital inputs and outputs. With Circuitpython it's super easy!

This quick-start example shows how you can turn one of the Gemma pads into a button input with pullup resistor (built in) and then use that to control another digital output - the built in LED

Copy and paste the code block into using your favorite text editor, and save the file, to run the demo

# CircuitPython IO demo #1 - General Purpose I/O

from digitalio import DigitalInOut, Direction, Pull
import board
import time

led = DigitalInOut(board.D13)
led.direction = Direction.OUTPUT

button = DigitalInOut(board.D2)
button.direction = Direction.INPUT
button.pull = Pull.UP

while True:
    # we could also just do "led.value = not button.value" !
    if button.value:
		led.value = False
		led.value = True

    time.sleep(0.01) # debounce delay

Note that we made the code a little less 'pythonic' than necessary, the if/then could be replaced with a simple led.value = not button.value but I wanted to make it super clear how to test the inputs. When the interpreter gets to evaluating button.value that is when it will read the digital input.

Find the pin or pad labeled D2 (sometimes just 2) and use a wire to touch it to GND, the onboard red LED will turn on!

Note that on the M0/SAMD based CircuitPython boards, at least, you can also have internal pulldowns with Pull.DOWN and if you want to turn off the pullup/pulldown just assign button.pull = None

Last updated on 2017-12-01 at 04.59.09 PM Published on 2017-07-26 at 06.08.30 PM