CircuitPython Code

Trinket M0 boards can run CircuitPython — a different approach to programming compared to Arduino sketches. In fact, CircuitPython comes factory pre-loaded on Trinket M0. If you’ve overwritten it with an Arduino sketch, or just want to learn the basics of setting up and using CircuitPython, this is explained in the Adafruit Trinket M0 guide.

These directions are specific to the "M0” boards. The original Trinket and Gemma with an 8-bit AVR microcontroller doesn’t run CircuitPython…for those boards, use the Arduino sketch on the “Arduino code” page of this guide.

Below is CircuitPython code that works similarly (though not exactly the same) as the Arduino sketch shown on a prior page. To use this, plug the Trinket M0 into USB…it should show up on your computer as a small flash drive…then edit the file “main.py” with your text editor of choice. Select and copy the code below and paste it into that file, entirely replacing its contents (don’t mix it in with lingering bits of old code). When you save the file, the code should start running almost immediately (if not, see notes at the bottom of this page).

If Trinket M0 doesn’t show up as a drive, follow the Trinket M0 guide link above to prepare the board for CircuitPython.

# Trinket Gemma Servo Control
# for Adafruit M0 boards

import board
import pulseio
from adafruit_motor import servo
from analogio import AnalogIn

# servo pin for the M0 boards:
pwm = pulseio.PWMOut(board.A2, duty_cycle=2 ** 15, frequency=50)
my_servo = servo.Servo(pwm)
angle = 0

# potentiometer
trimpot = AnalogIn(board.A1)  # pot pin for servo control

def remap_range(value, left_min, left_max, right_min, right_max):
    # this remaps a value from original (left) range to new (right) range
    # Figure out how 'wide' each range is
    left_span = left_max - left_min
    right_span = right_max - right_min

    # Convert the left range into a 0-1 range (int)
    value_scaled = int(value - left_min) / int(left_span)

    # Convert the 0-1 range into a value in the right range.
    return int(right_min + (value_scaled * right_span))


while True:
    angle = remap_range(trimpot.value, 0, 65535, 0, 180)
    my_servo.angle = angle

This code requires an additional library be installed:

  1. adafruit_motor

If you’ve just reloaded the board with CircuitPython, create the “lib” directory and then download the Adafruit CircuitPython Bundle. You can copy 'adafruit_motor' folder into the lib directory.

Download: file
$ mkdir /Volumes/CIRCUITPY/lib 
$ cp -pr adafruit_motor /Volumes/CIRCUITPY/lib
This guide was first published on Sep 12, 2013. It was last updated on Sep 12, 2013.
This page (CircuitPython Code) was last updated on Aug 05, 2020.