Once you've finished setting up your KB2040 with CircuitPython, you can access the code and necessary libraries by downloading the Project Bundle.
To do this, click on the Download Project Bundle button in the window below. It will download to your computer as a zipped folder.
# SPDX-FileCopyrightText: Copyright (c) 2025 Liz Clark for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
Planetary Gear Dreidel Code - slightly modified from the STSPIN220 example
"""
import board
import adafruit_stspin
STEPS_PER_REVOLUTION = 200
DIR_PIN = board.D2 # DIRection pin
STEP_PIN = board.D3 # STEP pin
MODE1_PIN = board.D4 # Mode 1 pin (REQUIRED for mode switching)
MODE2_PIN = board.D5 # Mode 2 pin (REQUIRED for mode switching)
EN_FAULT_PIN = board.D6 # Enable/Fault pin (optional)
STBY_RESET_PIN = board.D7 # Standby/Reset pin (REQUIRED for mode switching)
print("Initializing STSPIN220...")
motor = adafruit_stspin.STSPIN(
STEP_PIN,
DIR_PIN,
STEPS_PER_REVOLUTION,
mode1_pin=MODE1_PIN,
mode2_pin=MODE2_PIN,
en_fault_pin=EN_FAULT_PIN,
stby_reset_pin=STBY_RESET_PIN,
)
# Set the speed to 60 RPM
motor.speed = 60
motor.step_mode = adafruit_stspin.Modes.STEP_1_128
while True:
# continuously step the motor
total_microsteps = STEPS_PER_REVOLUTION * motor.microsteps_per_step
motor.step(total_microsteps)
Upload the Code and Libraries to the KB2040
After downloading the Project Bundle, plug your KB2040 into the computer's USB port with a known good USB data+power cable. You should see a new flash drive appear in the computer's File Explorer or Finder (depending on your operating system) called CIRCUITPY. Unzip the folder and copy the following items to the KB2040's CIRCUITPY drive.
- lib folder
- code.py
Your KB2040 CIRCUITPY drive should look like this after copying the lib folder and the code.py file.
How the CircuitPython Code Works
The code begins by assigning variable names to the GPIO pins used with the STSPIN220.
DIR_PIN = board.D2 # DIRection pin STEP_PIN = board.D3 # STEP pin MODE1_PIN = board.D4 # Mode 1 pin (REQUIRED for mode switching) MODE2_PIN = board.D5 # Mode 2 pin (REQUIRED for mode switching) EN_FAULT_PIN = board.D6 # Enable/Fault pin (optional) STBY_RESET_PIN = board.D7 # Standby/Reset pin (REQUIRED for mode switching)
These pins are passed to the STSPIN initializer.
print("Initializing STSPIN220...")
motor = adafruit_stspin.STSPIN(
STEP_PIN,
DIR_PIN,
STEPS_PER_REVOLUTION,
mode1_pin=MODE1_PIN,
mode2_pin=MODE2_PIN,
en_fault_pin=EN_FAULT_PIN,
stby_reset_pin=STBY_RESET_PIN,
)
Before the loop, a few parameters are setup for motor speed, microstep mode and steps per revolution.
STEPS_PER_REVOLUTION = 200 motor.speed = 60 motor.step_mode = adafruit_stspin.Modes.STEP_1_128
In the loop, the motor is stepped continuously to rotate the gear mechanism.
while True:
# continuously step the motor
total_microsteps = STEPS_PER_REVOLUTION * motor.microsteps_per_step
motor.step(total_microsteps)
Page last edited December 11, 2025
Text editor powered by tinymce.