Software

Setup Adafruit Trinket M0 for CircuitPython

Your Trinket M0 should already come with CircuitPython but maybe there's a new version, or you overwrote your Trinket M0 with Arduino code! In that case, see the below for how to reinstall or update CircuitPython. Otherwise you can skip this and go straight to the next page.

Download Adafruit CircuitPython Library Bundle

The Trinket M0 needs to have the USB HID library in order to run the code, so check yours to see if it's in the lib folder. Otherwise, you can download it from the Library Bundle.  Unzip the downloaded file and look for the adafruit_hid library then drop it into the lib folder, create one if it's not already there. 

List of USB HID Keycodes

The long list of available keyboard characters are listed in the webpage linked below. Most of the characters are for USA keyboard only. Function keys and modifiers can be used but only some special characters are not supported.

Upload The Code

Copy and paste the code below into a new text document (we recommend using Mu as your editor, which is designed for CircuitPython.). Save the file and name it as main.py

Once the files has been uploaded to the drive, the Trinket M0 will automatically reboot and run the code.

Download: file
import digitalio
from board import *
import time
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.keycode import Keycode

# A simple neat keyboard demo in circuitpython
buttonpins = [D0]

# The keycode sent for each button, optionally can be paired with a control key
buttonkeys = [44]
controlkey = Keycode.LEFT_CONTROL

# the keyboard object!
kbd = Keyboard()

# our array of button objects
buttons = []

# make all pin objects, make them inputs w/pullups
for pin in buttonpins:
    button = digitalio.DigitalInOut(pin)
    button.direction = digitalio.Direction.INPUT
    button.pull = digitalio.Pull.UP   
    buttons.append(button)
 
print("Waiting for button presses")

while True:
    # check each button
    for button in buttons:
        if (not button.value):   # pressed?
            i = buttons.index(button)
            
            print("Button #%d Pressed" % i)

            # type the keycode!
            k = buttonkeys[i]    # get the corresp. keycode
            kbd.press(k)
            # Use this line for key combos kbd.press(k, controlkey)
            kbd.release_all()

            while (not button.value):
                pass  # wait for it to be released!
    time.sleep(0.01)
This guide was first published on Mar 21, 2018. It was last updated on Mar 21, 2018. This page (Software) was last updated on Jul 15, 2019.