8. With a 12 MHz reference, what is the standard PLL_SYS calculation for 125 MHz? 12 MHz ÷ 125 × 6 × 2. (12 MHz × 125) ÷ (6 × 2). 12 MHz + 125 MHz. 12 MHz × 6 × 2 ÷ 125.
9. In normal edge-aligned PWM, with clk_sys = 125 MHz, divider D = 1, and TOP = 6249, what is the frequency? 1 kHz. 10 kHz. 125 kHz. 20 kHz.
10. For a PWM period of 6250 counter ticks, approximately how many HIGH ticks give a 40% duty cycle?
1.2.11 Calculation tutorial: ADC, clock, and PWMWork through each example in order. Keep the units visible, and check whether a calculated TOP value is within the RP2040’s 0–65,535 range.
Example 1 — Convert a 1.65 V input to an ideal 12-bit ADC code Assume a 3.3 V ADC reference. A 12-bit converter has 212 = 4096 codes, numbered 0 to 4095.
Vref reference voltage (V) round round to the nearest integer Vin input voltage (V) code raw ADC code V voltage (V) ADC code ≈ round[(Vin ÷ Vref ) × (212 − 1)] ≈ round[(1.65 V ÷ 3.3 V) × 4095] = round[0.5 × 4095] = 2048
CircuitPython scales this 12-bit measurement to its 16-bit AnalogIn.value range, so the displayed value is approximately 32768 out of 65535. This is an ideal calculation; real ADC readings can vary slightly.
Example 2 — Derive clk_sys from the 12 MHz crystal reference For the standard PLL_SYS settings, feedback multiplier = 125, POSTDIV1 = 6, POSTDIV2 = 2.
fsys system-clock frequency (Hz) fVCO PLL voltage-controlled oscillator frequency (Hz) fVCO = 12 MHz × 125 = 1500 MHz fsys = 1500 MHz ÷ (6 × 2) = 125 MHz
The PLL synthesizes clk_sys; the 12 MHz crystal is the stable timing reference.
Example 3 — Choose TOP for a 20 kHz PWM signal For normal edge-aligned PWM, solve the frequency equation for TOP. Use clk_sys = 125 MHz and divider D = 1.
fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) fPWM = fsys ÷ [D × (TOP + 1)] TOP = fsys ÷ (D × fPWM ) − 1 TOP = 125,000,000 ÷ (1 × 20,000) − 1 = 6249
Check: TOP is within 0–65,535. The period is TOP + 1 = 6250 counter ticks, and 125,000,000 ÷ 6250 = 20,000 Hz.
Example 4 — Calculate the compare count for 40% duty cycle At TOP = 6249, the period contains 6250 ticks. Approximate the number of HIGH ticks using the target duty ratio.
CHIGH number of HIGH counter ticks C counter counts per PWM period d duty ratio, from 0 to 1 (dimensionless) p percentage on a 0–100 scale (%) CHIGH ≈ d × C CHIGH ≈ 0.40 × 6250 CHIGH = 2500 p = (CHIGH ÷ C) × 100 p = (2500 ÷ 6250) × 100 p = 40%
On RP2040, the channel compare value controls when the output changes within the count period; the 0% and 100% boundary cases use compare values 0 and TOP + 1 respectively.
Example 5 — Estimate voltage from a 12-bit ADC code An ideal 12-bit ADC code of 1024 represents a fraction of the 0–4095 range. Use a 3.3 V reference.
Vref reference voltage (V) Vin input voltage (V) code raw ADC code V voltage (V) Vin ≈ (ADC code ÷ 4095) × Vref = (1024 ÷ 4095) × 3.3 V ≈ 0.826 V
This is an ideal estimate; the real reading may differ slightly.
Example 6 — Convert a 16-bit CircuitPython ADC reading to voltage If AnalogIn.value displays 49151, estimate the voltage using the 16-bit range 0–65535 and a 3.3 V reference.
Vref reference voltage (V) Vin input voltage (V) V voltage (V) r CircuitPython ADC reading on the 0–65,535 API scale Vin ≈ (r ÷ 65535) × Vref = (49151 ÷ 65535) × 3.3 V ≈ 2.475 V
Example 7 — Find the period of a 20 kHz PWM signal Frequency tells how many cycles occur each second. The period is the time for one cycle.
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) s shaft speed (revolutions/minute, rpm) T = 1 ÷ f = 1 ÷ 20,000 s = 0.00005 s = 50 µs
Example 8 — Find HIGH and LOW times at 40% duty Use the 50 µs period from Example 7. A 40% duty cycle means the signal is HIGH for 40% of the period.
T period of one cycle (s unless another time unit is stated) TON HIGH time within one period (same time unit as T) TOFF LOW time within one period (same time unit as T) d duty ratio, from 0 to 1 (dimensionless) TON = d × T TON = 0.40 × 50 µs TON = 20 µs TOFF = T − TON TOFF = 50 µs − 20 µs TOFF = 30 µs
Example 9 — Choose a divider for a 1 kHz PWM signal With clk_sys = 125 MHz, first try D = 1. The resulting TOP is too large for the 16-bit counter, so choose D = 2.
TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP = fsys ÷ (D × fPWM ) − 1 TOP = 125,000,000 Hz ÷ (1 × 1000 Hz) − 1 TOP = 124,999
The first result exceeds 65,535. Increase the divider to 2 and recalculate.
TOP = 125,000,000 Hz ÷ (2 × 1000 Hz) − 1 TOP = 62,499 fPWM = 125,000,000 Hz ÷ [2 × (62,499 + 1)] fPWM = 1000 Hz
TOP = 62,499 is within the permitted 0–65,535 range.
Example 10 — Convert 40% duty to CircuitPython’s 16-bit value CircuitPython’s PWMOut.duty_cycle uses a value from 0 (always LOW) to 65,535 (always HIGH). To request 40%:
round round to the nearest integer u integer CircuitPython duty setting, from 0 to 65,535 u ≈ round[(40 ÷ 100) × 65,535] = 26,214
This is the software duty setting. The PWM frequency is configured separately.
Key ideas to retain The RP2040 is the chip, Pico W is the controller board, and EDU PICO is the learning platform. The processor executes the program; pins and interfaces connect it to signals and devices. GPIO handles logic signals; ADC reads supported analogue voltages; PWM provides timed outputs; I²C uses SDA and SCL. For the booklet’s EDU PICO examples, I²C uses SDA GP4 and SCL GP5. Power, ground, reset, clock, and suitable driver circuits are part of understanding the complete hardware system.
REFERENCES AND CONTINUITY
Materials used Cytron, Explore STEM and Coding with EDU PICO , Version 2.0: start-up and board operation (p. 12); reset/BOOTSEL procedure (p. 16); Button A on GP0 (pp. 29–30); OLED wiring and example (pp. 48–49); greenhouse device and interface map (pp. 164–168); relay GP22 (pp. 173–177). EDI4153 original Chapter 1 material and the agreed RP2040/CircuitPython subtopic outline. RP2040-based EDU PICO course examples in 20262027/lecture_examples. Next, topic 1.3 develops the CircuitPython software workflow used to write, run, and debug programs on this hardware. Detailed device operation is covered in Chapters 2 and 3, with hardware architecture revisited in Chapter 5.
CHAPTER 1 / SUBTOPIC 1.3
1.3 Software development for the microcontroller Developed lecture notes RP2040 · CircuitPython · Thonny · EDU PICO
In this subtopic, we move from understanding the hardware to writing, running, and checking a program on it. Thonny is the development environment on the computer; CircuitPython is the interpreter running on the microcontroller; code.py is the program file the board executes.
01 / PLAN THE PROGRAM
1.3.1 From a need to an algorithmBefore writing Python, state the task in plain language. For example: “When Button A changes state, report whether it is pressed or released.” Break the task into steps, then trace the decisions before coding.
Start the program and configure Button A’s GP0 pin as a digital input with a pull-up. Initialize last_pressed so the first reading is reported. Repeat: read the pin and convert the active-low logic level into a pressed/released state. Check whether the state differs from the previous reading. If it changed, print the new state and store it as the previous state. Wait briefly, then read the pin again. Button A state-change flowchart Start, configure GP0 with a pull-up, initialize the previous state, read and invert the active-low button value, decide whether the state changed, print and update only when it changed, wait 20 milliseconds, and repeat. START Configure GP0 input + pull-up last_pressed = None Read Button A pressed = NOT button.value State changed? pressed ≠ last_pressed YES NO · skip print Print pressed / released Update last_pressed continue Wait 20 ms REPEAT LOOP Figure 1.12. Flowchart for the active-low Button A state-change program. Both decision paths return to the input read; the program prints only when the button state changes.The decision and state update in this flowchart match the guided program in 1.3.7; they prevent the Shell from printing the same state continuously.
Pseudocode SET GP0 as input with pull-up
SET last_pressed = None
REPEAT forever:
pressed = NOT button.value
IF pressed is different from last_pressed:
IF pressed:
print “Button A pressed”
ELSE:
print “Button A released”
last_pressed = pressed
WAIT 20 ms
02 / THONNY DEVELOPMENT ENVIRONMENT
1.3.2 Read the Thonny workspace and toolbarThonny combines a code editor with controls for running and debugging a program, a Shell for output and interactive commands, and optional panes such as Files. This teaching mockup labels the main regions and common actions; it is a schematic, not a screenshot. Actual button icons, panel positions, and menus can vary by Thonny version and operating system.
Thonny · Python IDE − □ ×
+ New
Open
Save
▶ Run · F5
Debug
■ Stop / Restart
① Files pane Browse local files and, when supported/configured, files on the board.
View → Files
② Editor · code.py print("EDI4153")
print("Program running")Write and edit the program here. ③ Shell / console EDI4153
Program running
>>> Program output, REPL prompt, and error messages appear here.
④ Interpreter / backend: CircuitPython device ⑤ Status: line 1 · connected
Select a toolbar button above to see what it does.
GUI control or area Function in the lesson
New, Open, Save Create, open, and save source files. Keep a local backup; copy the runnable file to the board as code.py when it should run automatically.
Run current script · F5 Execute the editor’s current program with the selected interpreter. Look at the Shell for printed output.
Debug current script Start step-by-step execution. In the debugger, Step over executes the current line, Step into follows a function call into its code, and Step out finishes the current function. Menu names and shortcuts can vary by release.
Stop / restart backend Interrupt a program that is running continuously or reset the interpreter connection.
Editor Area where Python statements are written and edited. Syntax highlighting can help distinguish names, strings, and keywords.
Shell / console Shows print() output and tracebacks; its >>> prompt can accept interactive Python commands when the board is connected.
Files pane and interpreter/backend status Help locate scripts and confirm which Python environment or connected microcontroller Thonny is using. Select the CircuitPython backend/device, not desktop Python or a different MicroPython target.
Thonny setup labels may differ: the course booklet’s screenshots show the interpreter selector and firmware installer in a particular version. In other versions, use Run → Select interpreter , the interpreter selector in the status bar, or Tools → Options → Interpreter . CircuitPython may appear as a generic backend or require the matching Thonny support plugin. If the board already shows a CIRCUITPY drive and the Shell identifies CircuitPython, do not reinstall firmware just to begin coding. See the Thonny setup in Subtopic 1.3 .
03 / CONNECT THE BOARD
1.3.3 Connect the EDU PICO and check the firmwareThonny runs on the computer, but the CircuitPython program runs on the microcontroller. The interpreter setting determines where Thonny sends the code.
Connect the EDU PICO using a USB cable that supports data. In Thonny, select the CircuitPython interpreter/device and its serial connection. If the Shell reports desktop CPython or a different firmware, select the correct backend. Check whether the board exposes its CIRCUITPY drive. If CircuitPython is already installed and the drive is available, continue without reinstalling firmware. Only when firmware is missing, damaged, or incompatible, install the CircuitPython build intended for the exact microcontroller board. Follow the board-specific instructions; BOOTSEL/UF2 recovery is not needed for routine editing. Install the matching CircuitPython library bundle only when the program imports external libraries. Start with a simple built-in example before adding dependencies. Firmware is not the student program. Firmware supplies the CircuitPython runtime that interprets Python on the board. A file such as code.py contains the application instructions written by the student.
The course examples include a simple startup check in 01_hello.py and a Button A example in 09_buttons.py . The examples README explains which files need libraries and which target the EDU PICO hardware.
04 / WRITE, SAVE, RUN
1.3.4 Create and run code.pyFor the first test, use a short program that does not require a sensor or library:
print("EDI4153: application starting")
print("Hello from the EDU PICO")Create a new file in the editor. Choose Run current script (commonly F5). Read both output lines in the Shell. Save a copy on the computer so the original work is backed up. For automatic execution by CircuitPython, save/copy the program to the root of the CIRCUITPY drive with the exact name code.py. After the file is saved, CircuitPython normally reloads and runs code.py; its output appears in the serial Shell. Keep only the program you intend to run automatically under that name. Run from editor versus run at startup: the Run button asks the currently selected backend to run the open editor contents. CircuitPython’s startup workflow runs the saved code.py file from the board. Saving another file on the computer alone does not replace the program on the board.
05 / INTERACTIVE CONSOLE
1.3.5 Use the Shell and REPL for quick experimentsREPL means Read–Evaluate–Print Loop . It reads a command, evaluates it, displays the result, and waits for another command. In Thonny, the Shell is the visible console area used for output and, when connected to a compatible device backend, interactive commands.
>>> 3 * 7
21
>>> print("Testing the console")
Testing the consoleThese commands are useful for checking small expressions or inspecting a value. They are not automatically saved as the contents of code.py. Use the editor for the program you want to keep. A long-running loop in code.py may need to be interrupted before the prompt is available.
Ask the Shell: What does the program print? Which line produced the output? If a traceback appears, which file and line number does it identify?
06 / READ AND FIX ERRORS
1.3.6 Distinguish syntax, runtime, and logic errorsError type What happens Example and debugging clue
Syntax error Python cannot parse the program, so it cannot start normally. print("Ready" is missing a closing parenthesis. Read the error location and check nearby brackets, quotes, colons, and indentation.
Runtime error The program starts, then an operation fails while it runs. print(10 / 0) raises a division-by-zero exception. Follow the traceback to the failing line.
Logic error The program runs but gives the wrong result. For an active-low button, treating button.value as “pressed” is reversed: a pull-up reads True when released. Compare the code’s condition with the wiring and observed state.
Read the complete Shell message, especially the exception type and reported line. Compare that line with the program and the expected algorithm. Change one thing at a time, save, and run again. Check the observed output or hardware state against the prediction. If a program is stuck in a loop, stop/restart it before editing or testing again. Thonny’s debugger can pause at statements. Step over is useful for following the algorithm line by line; Step into examines a called function; Step out returns from the current function. The Run menu also provides debugger controls; shortcut keys can differ by platform.
07 / GUIDED PRACTICAL
1.3.7 Mini-lab: Button A input to Shell messageThis beginner exercise uses the EDU PICO’s documented Button A connection on GP0. The button is active-low with a pull-up: released reads HIGH; pressed reads LOW. The loop prints only when the state changes.
import time
import board
import digitalio
button = digitalio.DigitalInOut(board.GP0)
button.switch_to_input(pull=digitalio.Pull.UP)
last_pressed = None
while True:
pressed = not button.value
if pressed != last_pressed:
if pressed:
print("Button A pressed")
else:
print("Button A released")
last_pressed = pressed
time.sleep(0.02)Predict Before running, predict the message at startup, after a press, and after release.
Run Save as code.py on the board or run it with the selected CircuitPython backend. Watch the Shell while operating Button A.
Explain Why does not button.value mean pressed? Which statements repeat? Why does the program print only after a state change?
Expected observation: the Shell reports “Button A released” at startup, then reports “Button A pressed” and “Button A released” as the button is operated. This short starter is for learning the workflow; robust mechanical-switch debouncing is studied with digital input topics later.
Extension tasks Change the message and predict the output before running the modified program. Intentionally remove a closing bracket. Record the syntax error and fix it. Change pressed = not button.value to pressed = button.value. Observe the reversed behavior and explain the logic error. Draw the algorithm as a flowchart and compare it with the running code.
08 / ADDITIONAL WORKED EXAMPLES
1.3.8 More examples and guided tutorialsUse these short tutorials after the first Button A activity. Each one practises a different part of the workflow: test an expression, run and trace a decision, build a hardware program, then diagnose common mistakes.
Tutorial A — Try an expression in the Shell, then save it in a program Click in the Thonny Shell at the >>> prompt and enter each line separately. >>> voltage = 1.65
>>> reference = 3.3
>>> voltage / reference
0.5
>>> print("Input is at", voltage, "V")
Input is at 1.65 VThe Shell evaluates commands immediately, but these commands are not a saved lesson file. To keep and rerun them, place the statements in the editor and save the program. For example:
voltage = 1.65
reference = 3.3
ratio = voltage / reference
print("Fraction of reference:", ratio)Expected output: Fraction of reference: 0.5. Try changing voltage to 2.4 and predict the fraction before pressing Run.
Tutorial B — Run and trace a decision in the debugger This example uses a simulated temperature so students can practise Python decisions without needing to connect a sensor.
temperature_c = 28
set_point_c = 30
print("Measured:", temperature_c, "°C")
if temperature_c > set_point_c:
print("Fan command: ON")
else:
print("Fan command: OFF")
print("Program finished")Run it and confirm that 28°C produces Fan command: OFF. Change the temperature to 33°C and predict the result. To trace the control flow, start Debug current script , then use Step over to execute one statement at a time. Observe when the condition is tested and which branch runs. If available, show the Variables view to inspect temperature_c and set_point_c.
Worked reasoning At 28°C, 28 > 30 is false, so the else branch prints OFF. At 33°C, 33 > 30 is true, so the first branch prints ON. The indentation groups each branch under the condition; the program does not execute both messages.
Tutorial C — Count Button A presses with debouncing The first lab prints a message for each state change. This extension counts press events and uses the adafruit_debouncer library to reduce duplicate events caused by mechanical contact bounce. It follows the style of the course’s 09_buttons.py example.
import board
import digitalio
from adafruit_debouncer import Debouncer
button_pin = digitalio.DigitalInOut(board.GP0)
button_pin.switch_to_input(pull=digitalio.Pull.UP)
button = Debouncer(button_pin, interval=0.02)
press_count = 0
while True:
button.update()
if button.fell:
press_count += 1
print("Button A presses:", press_count)Confirm that the matching adafruit_debouncer library is installed in CIRCUITPY/lib; otherwise the import will raise an error. Save this program as code.py, run it, and press Button A three times. Explain why button.fell indicates a press for this active-low, pull-up arrangement. Expected output: Button A presses: 1, then 2, then 3. Releasing the button does not increment the count. The 20 ms interval is the debounce interval used in the course example; it is not a universal value for every switch.
Tutorial D — Find and fix the error Use Thonny’s Shell message, highlighted line, wiring knowledge, and the intended algorithm to identify each problem before opening the answer guide.
Program fragment Your diagnosis print("Board ready"Is this a syntax, runtime, or logic error? if temperature_c = 30:Why can Python not evaluate this condition? pressed = button_pin.valueWhat state does this produce when an active-low button is released? from adafruit_debouncer import Debouncer followed by ImportErrorWhat should be checked before changing the button logic?
Reveal diagnoses and corrections print("Board ready" has a missing closing parenthesis: a syntax error. Correct it to print("Board ready").Use == to compare values; a single = is assignment and is invalid in this if condition. Write if temperature_c == 30:. With a pull-up, the released button reads True, so this assignment reverses the intended “pressed” meaning. Use pressed = not button_pin.value or test the debouncer’s event property. The library is missing or stored in the wrong place, or the selected board firmware/library bundle is incompatible. Confirm the library exists in CIRCUITPY/lib and matches the CircuitPython setup before editing the program logic.
Independent practice Modify Tutorial B to print “Check sensor” when the reading equals the set point. Modify Tutorial C to report both the press count and the active-low logic level when Button A is pressed. In your lab record, include the prediction, code change, observed Shell output, and one sentence explaining any mismatch.
REFERENCES AND CONTINUITY
Review and materials By the end of 1.3, students should be able to: describe the editor, toolbar and Shell; choose the board interpreter; save and run code.py; use the REPL for a short test; classify common errors; and trace a simple algorithm from input to output.
Subtopic 1.3 establishes the development workflow. The later system-output, system-input, and software chapters build on this workflow to develop larger programs.
CHAPTER 02
System Outputs YOUR LEARNING GOALS
Chapter 2 learning outcomes By the end of this chapter, students should be able to:
Distinguish output devices from the information or physical actions they produce, and select a suitable indicator, display, or actuator for a stated application. Construct a CircuitPython program using imports, initialization, functions, and a repeating loop to control digital outputs, GPIO indicators, RGB LEDs, a buzzer, and the USB relay. Derive seven-segment digit patterns, explain common-anode/common-cathode operation and multi-digit scanning, and apply these principles to the M18 TM1650 four-digit display practical. Initialize the EDU PICO OLED using the adafruit_ssd1306 library and display text, numerical values, and system status at specified screen positions. Calculate PWM period, frequency, and duty cycle, and configure suitable waveforms for a specified output task. Compare DC, stepper, and servo motor operation; implement DC and servo control with EDU PICO; and determine the coil sequence and additional hardware needed for a stepper-motor application. Select a subtopic to view its planned coverage.
12 topics 2.1–2.11 developed · 2.12 to follow
CHAPTER 2 / SUBTOPIC 2.1
2.1 Introduction to system outputs Lesson developed RP2040 · CircuitPython · EDU PICO
An embedded system does more than read inputs and make decisions. It also sends signals to communicate information or make something happen.
2.1.1 From a program decision to an output
Output signal: a signal produced by a controller to communicate a value or command to another part of the system.
Output device: a component that responds to a controller’s signal and produces a result that a person or another system can observe.
The signal is the controller’s instruction; the device is what responds. For example, a GPIO pin may send a digital HIGH signal, while an LED connected through a suitable circuit produces light. The signal and the visible result are related, but they are not the same thing.
How an embedded system produces an output A program decision creates a controller output signal, which reaches a suitable interface and output device to produce an observable result. PROGRAM decision CONTROLLER output signal INTERFACE if required DEVICE observable result Figure 2.1. General path from a program decision to a result. Some devices need an interface or driver; its purpose and design are covered with the relevant device later in this chapter.
2.1.2 Three useful groups of output devicesStart by reading each highlighted definition. Then open the card to see the device’s function and an example.
Indicator Definition: an output device that communicates a simple status or condition. Open for function and example Function: lets a person recognize a state quickly, often through light or sound.
Example: an LED that shows whether a system is active or an alert buzzer that signals a warning.
Display Definition: an output device that presents information in a form people can read. Open for function and example Function: communicates values, messages, or several pieces of system information.
Example: a seven-segment display showing a number or an OLED showing a short status message.
Actuator Definition: an output device that converts a control signal into a physical action. Open for function and example Function: changes something in the physical environment, such as producing movement.
Example: a motor turning a fan or a servo moving a small mechanism.
One device can serve different purposes in different systems. Classify it by the role it plays in the application. A buzzer, for example, can act as an indicator when it signals an alarm.
2.1.3 Explore one condition and different outputsImagine a water-tank system detects that the tank is full. The program makes one decision—tank full —and can communicate it in several ways. Select an output to see what a person would observe.
System condition Tank is full Program decision: warn the user
LED indicator Text display Buzzer
Indicator: the LED turns on to show that the tank is full.
The condition stays the same; the selected output changes how the system communicates the warning.
2.1.4 Check your understandingChoose the best category for each example. You’ll get immediate feedback.
1. A lamp lights when a device is powered on.
Indicator Display Actuator
2. A small screen shows the measured temperature as text and numbers.
Indicator Display Actuator
3. A motor moves a vent to change airflow.
Indicator Display Actuator
Key idea: an embedded system produces an output signal; an output device responds and creates information or an action. Indicators communicate status, displays present readable information, and actuators cause physical change.
CHAPTER 2 / SUBTOPIC 2.2
2.2 Program template Lesson developed RP2040 · CircuitPython · EDU PICO
A program template is a familiar structure that helps you organize code before you add the details of a particular application.
2.2.1 A simple program has three main partsProgram template: a reusable arrangement of code sections that gives a program a clear starting structure.
1 · Import Make the required modules available.
↓ 2 · Initialize Prepare the devices and pins before use.
↓ 3 · Main loop Repeat the actions the application needs.
This pattern appears in many embedded programs. Imports and setup normally run once when the program starts; the main loop runs repeatedly until the program is stopped or the board is reset.
2.2.2 Import the tools the program needsImport statement: a Python instruction that makes names from a module available to a program.
A module is a file or package of reusable code. CircuitPython modules provide access to board pins, device features, and time-related functions. Import only what this program uses:
import board
import digitalio
import timeboard provides names for pins and board connections.digitalio provides tools for digital input and output.time provides timing functions such as sleep().For example, after import time, the program can call time.sleep(1) to pause for one second. Library installation and device-specific libraries are covered when they are needed in later lessons.
2.2.3 Initialize devices before using themInitialization: the setup instructions that prepare a device or resource for use.
In this example, the program creates a digital output object for GP15 and sets its direction. This setup is outside the loop because it only needs to happen once at startup.
# Configure GP15 as a digital output
led = digitalio.DigitalInOut(board.GP15)
led.direction = digitalio.Direction.OUTPUTThe example assumes a suitable indicator circuit is connected to GP15. Use the EDU PICO pin map and the relevant later section to confirm the real connection and any required interface before running hardware. Here, focus on where initialization belongs in the program.
2.2.4 Repeat the application in a main loopMain loop: a section of code that repeatedly checks or controls the system while the program is running.
Python’s while True: starts a loop that continues until execution is interrupted or the board is reset. Instructions indented under it belong to the loop and run again each pass.
while True:
led.value = True
time.sleep(1)
led.value = False
time.sleep(1)Read this example as: set the output on, wait one second, set it off, wait one second, then return to the first indented instruction. The result is a repeating on/off pattern.
2.2.5 Read the complete templateSelect a code section to highlight it and see when it runs.
1. Imports 2. Initialization 3. Main loop
import board
import digitalio
import time
# Configure GP15 as a digital output
led = digitalio.DigitalInOut(board.GP15)
led.direction = digitalio.Direction.OUTPUT
while True:
led.value = True
time.sleep(1)
led.value = False
time.sleep(1) Imports run once: Python loads the names the program will use before it begins setup.
2.2.6 Comments, names, and indentationComment: text in source code for human readers that Python does not execute.
A comment begins with #. In the example, # Configure GP15 as a digital output explains the following setup line. Comments should clarify why code is present rather than repeat what the line already says.
Indentation: the spaces at the beginning of a line that show which statements belong inside a code block.
In Python, indentation is part of the program’s structure. The four indented lines under while True: repeat. If one of those lines is moved back to the left margin, it no longer belongs to the loop. Keep indentation consistent, commonly four spaces per level.
Names such as led should describe the resource they represent. Clear names and brief comments help you and your classmates trace the program.
2.2.7 Check your understandingChoose whether each instruction normally runs once during startup or repeatedly inside the main loop.
1. led.direction = digitalio.Direction.OUTPUT
Once at startup Repeated in the loop
2. led.value = not led.value when placed inside while True:
Once at startup Repeated in the loop
Template to remember: import what you need → initialize devices once → repeat the application in the main loop. Comments explain intent, and indentation shows which instructions repeat.
CHAPTER 2 / SUBTOPIC 2.3
2.3 Built-in and library functions Lesson developed RP2040 · CircuitPython · EDU PICO
CircuitPython programs use functions to perform common tasks: display information, calculate with sensor readings, pause, and control devices.
2.3.1 What is a function?Function: a named operation that performs a task when the program calls it.
A function call consists of a function name followed by parentheses. Information placed inside the parentheses is passed to the function. A function may give a result back to the program, or it may perform an action without returning a useful result.
len (readings )Function name: len Argument: readings Returned result: number of items in the collection
2.3.2 Built-in functions used in EDU PICO programsBuilt-in function: a function Python provides directly, so the program can call it without importing a separate module.
These built-ins appear in the supplied EDU PICO CircuitPython examples. Select one to inspect its definition, arguments, returned result, and practical use.
print() range() len() sum() int()
Definition: Writes information to the serial console, such as Thonny’s Shell.
Arguments: One or more values to display; text and numbers can be supplied together.
Returned result: None. Its purpose is to display information.
print("Pot V:", voltage)EDU PICO use: Report sensor values and system status while testing a program.
How several built-ins work together The EDU PICO potentiometer example collects 16 ADC readings. len() gets the sample count, sum() adds the readings, and division calculates the average. print() reports the measured voltage and position.
readings = [pot.value for _ in range(16)]
average = sum(readings) / len(readings)
voltage = average * pot.reference_voltage / 65535
percent = average * 100 / 65535
print("Pot V:", voltage, "Position %:", percent)int() is useful when a calculation produces a decimal but an integer setting is required. For example, an integer PWM duty value can be calculated from a percentage:
duty = int(percent * 65535 / 100)This calculation illustrates conversion to an integer; detailed PWM operation is covered in Subtopic 2.9. In Python, int() truncates the fractional part toward zero; it does not round to the nearest integer.
These examples follow the local Chapter 4: Programming Fundamentals and EDU PICO potentiometer example . Other course examples use range() for repeated steps and sweeps.
2.3.3 Functions from modules and device objectsNot every function call is a built-in. The part before the dot tells you where to find the operation:
Built-in function Definition: supplied by Python and available without importing its own module.
len(readings)Here len() is a built-in.
Module function Definition: a function provided by an imported module.
time.sleep(0.5)sleep() comes from the imported time module.
Device method Definition: an operation provided by a particular object or device.
microphone.record(samples, count)record() is a method of the microphone object.
A class constructor such as digitalio.DigitalInOut(pin) creates a hardware object. It is not a built-in function. Recognizing these categories helps you know whether a call needs an import, a device object, or neither.
2.3.4 Make a small function of your ownUser-defined function: a named block of code written by the programmer to perform a particular task.
Use def to define the function. The names in its parentheses are parameters ; the values supplied when calling it are arguments . return sends a result back to the calling line.
def adc_to_voltage(adc_value, reference_voltage):
return adc_value * reference_voltage / 65535
voltage = adc_to_voltage(32768, 3.3)
print("Voltage:", voltage)Here, adc_value and reference_voltage are parameters. The call passes 32768 and 3.3 as arguments. The returned voltage is stored in voltage. This short example illustrates function structure; later topics use reusable functions in larger device programs.
Five more functions used in EDU PICO lessons Open each example to see its job, inputs, result, and any hardware effect. These functions come from the supplied CircuitPython and EDU PICO lesson materials.
set_rgb_colour(pixels, colour)Set all EDU PICO RGB LEDs to a selected colour Inputs: the NeoPixel strip object and an RGB colour tuple, such as (0, 30, 0) for green.
Returns: no value. It changes the pixels and sends the new colour to the LEDs.
Role: combine the two output operations used by the EDU PICO NeoPixel example in one reusable function. The board has five WS2812 RGB pixels on GP14.
def set_rgb_colour(pixels, colour):
pixels.fill(colour)
pixels.show()Adapted from: EDU PICO RGB LED example .
set_angle(pwm, angle)Convert a servo angle into a PWM setting Inputs: a PWM output object and an angle in degrees (the lesson uses 0–180°).
Returns: no value. It changes the PWM object’s duty cycle to command the servo.
Role: hide the pulse-width calculation behind a meaningful name, so the main program can call set_angle(servo, angle).
def set_angle(pwm, angle):
pulse_us = 500 + angle * 2000 / 180
pwm.duty_cycle = int(pulse_us * 50 * 65535 / 1000000)Source: M14: Servo motor hardware module .
calculate_rms(values)Calculate a sound-signal level from a sample buffer Input: a collection of microphone samples.
Returns: a numeric RMS magnitude. The example first finds the mean, then calculates the square root of the average squared difference from that mean.
Role: turn many raw microphone samples into one value the program can display or compare.
def calculate_rms(values):
average = sum(values) / len(values)
total = 0.0
for sample in values:
total += (sample - average) * (sample - average)
return math.sqrt(total / len(values))Source: M07: PDM microphone hardware module .
set_relay(enabled)Set the EDU PICO relay output from a Boolean state Input: True to enable or False to disable.
Returns: no value. It changes the relay output object initialized elsewhere in the program.
Role: give the output action a clear name so the main loop can express intent, for example set_relay(alarm_active). This example depends on a previously configured relay object.
def set_relay(enabled):
relay.value = bool(enabled)Source: EDU PICO lecture notes, output program template .
next_fan_state(temperature, running, on_c=30.0, off_c=28.0)Choose whether a temperature-controlled fan should run Inputs: temperature, the current running state, and optional ON/OFF thresholds.
Returns: True or False for the next fan state. Between 28°C and 30°C it keeps the current state, preventing rapid switching near one threshold.
Role: separate the temperature decision from the code that controls the motor output.
def next_fan_state(temperature, running, on_c=30.0, off_c=28.0):
if temperature is None:
return False
if temperature >= on_c:
return True
if temperature <= off_c:
return False
return runningSource: EDU PICO hysteresis example .
Compare the effects: calculate_rms() and next_fan_state() return useful results; set_rgb_colour(), set_angle(), and set_relay() change hardware state and do not return a useful value. A function can calculate a value, prepare an object, or control a device.
2.3.5 Identify the kind of function callChoose the best category for each example. Immediate feedback explains the distinguishing clue.
1. len(samples)
Built-in Module function Device method User-defined
2. time.sleep(1)
Built-in Module function Device method User-defined
3. microphone.record(samples, count)
Built-in Module function Device method User-defined
4. adc_to_voltage(32768, 3.3)
Built-in Module function Device method User-defined
Key idea: recognize what the call does, what arguments it receives, and whether it returns a value. The name before a dot often identifies a module or object that provides the function.
CHAPTER 2 / SUBTOPIC 2.4
2.4 Output operations Lesson developed RP2040 · CircuitPython · EDU PICO
A program controls a digital output by configuring a GPIO pin and setting its logic state. The circuit determines how the connected device responds.
2.4.1 Configure a GPIO pin as an outputDigital output: a controller signal set to one of two logic states, LOW or HIGH.
Initialization: setting up a pin’s direction and starting state before the program uses it.
In CircuitPython, digitalio.DigitalInOut() creates an object for a GPIO pin. Calling switch_to_output(value=False) configures it as an output and gives it a known initial value. Starting in a deliberate state helps prevent an unintended brief action when the program begins.
import board
import digitalio
output = digitalio.DigitalInOut(board.GP22)
output.switch_to_output(value=False)The example uses GP22, the EDU PICO USB relay control pin. In this lesson’s program, False is the initial disabled state. Other hardware may require a different pin and starting state.
2.4.2 Set and understand the output valueOutput value: the Boolean state written to the output pin: False for LOW or True for HIGH.
For RP2040 GPIO, LOW is approximately 0 V and HIGH is approximately 3.3 V. Setting the object’s .value property changes the logic state:
output.value = True # drive the pin HIGH
output.value = False # drive the pin LOWThe pin supplies a control signal. It is not a general-purpose power supply for motors, relays, or other high-current loads. EDU PICO has onboard driver circuits for some devices; use the proper board connection for each device.
2.4.3 Active-high and active-low outputsActive-high: a device or circuit is considered active when its control signal is HIGH.
Active-low: a device or circuit is considered active when its control signal is LOW.
These simplified external-LED schematics show how the load connection determines which GPIO state turns the device on. The resistor limits LED current in both circuits.
Interactive GPIO output level Set GPIO LOW Set GPIO HIGH
GPIO output: LOW · approximately 0 V
Active-high · GPIO sources current Active-high LED output schematic An RP2040 GPIO output connects through a 330 ohm current-limiting resistor and an LED to ground. A HIGH output drives current and turns on the LED. RP2040 GPIO output 330 Ω LED I GND LED state: OFF · active when HIGH
When GPIO is HIGH, current flows out of the pin, through the resistor and LED, to ground.
Active-low · GPIO sinks current Active-low LED output schematic 3.3 volts connects through a 330 ohm current-limiting resistor and LED to an RP2040 GPIO output. A LOW output sinks current and turns on the LED. 3.3 V supply 330 Ω LED I RP2040 GPIO output LED state: ON · active when LOW
When GPIO is LOW, current flows from 3.3 V through the resistor and LED into the pin, which sinks current.
Figure 2.2. Generic 3.3 V GPIO circuits for learning output polarity. These do not depict the EDU PICO relay wiring; the relay uses its onboard switching circuit.“Active” describes the meaning of the signal in the circuit. It does not change what HIGH and LOW mean electrically. Use the controls inside the figure to change the shared GPIO level; both circuit states and the LED symbols update together.
2.4.4 Repeat an output operationPlace changing output instructions inside a loop when the application needs to act repeatedly. In this short example, the software alternates a GPIO output between HIGH and LOW. The indentation shows which instructions repeat.
import time
while True:
output.value = True
time.sleep(1)
output.value = False
time.sleep(1)This creates a repeating one-second ON/one-second OFF pattern for a suitable connected circuit. The connected device’s response still depends on whether its control input is active-high or active-low.
2.4.5 EDU PICO USB relay on GP22The EDU PICO USB relay is controlled through GP22. The onboard circuit uses the GPIO as a low-current control signal and switches power along the USB relay path. In the course example, relay.value is used as the software state: False means disabled and True means enabled.
GP22 · USB relay simulation Choose a control state to see the software value and simulated USB power status.
Disable relay Enable relay
● Software value: False · USB power: disabled
This is a software simulation; it does not switch the physical board. For a classroom hardware test, follow the EDU PICO instructions and use only a suitable low-power USB load.
EDU PICO relay program This pattern follows the supplied relay example: configure GP22 LOW at startup, toggle the output periodically, and set it LOW and release the pin when the program stops.
import board
import digitalio
import time
relay = digitalio.DigitalInOut(board.GP22)
relay.switch_to_output(value=False)
try:
while True:
relay.value = not relay.value
print("USB relay enabled:", relay.value)
time.sleep(1)
finally:
relay.value = False
relay.deinit()try: begins a block of code that the program attempts to run. Here, the relay loop is inside that block. finally: introduces cleanup instructions that run when execution leaves the try block—for example, when the program is stopped or an error interrupts the loop. The cleanup sets the relay state to disabled and deinit() releases the GPIO resource. There is no except block here, so finally does not hide or fix an error; it cleans up, then the error can still be reported. Abrupt power loss or reset may prevent software cleanup from running.
Source examples: M16: USB relay hardware module ; EDU PICO GP22 relay schedule . The teaching material maps the onboard USB relay to GP22 (booklet reference in the source lesson: pp. 12 and 130–150).
2.4.6 Check your understandingChoose the best answer. Each response explains what the code or signal means.
1. What does relay.switch_to_output(value=False) do?
Configures the pin as an output and starts LOW Starts HIGH Configures the pin as an input
2. In an active-low circuit, when is the device active?
When the signal is HIGH When the signal is LOW At both levels
3. In the supplied GP22 relay example, what starting value represents “disabled”?
True False None
Key idea: configure the pin, give it a deliberate starting state, then write HIGH or LOW as the application requires. Whether HIGH means “active” depends on the connected circuit.
CHAPTER 2 / SUBTOPIC 2.5
2.5 Light-emitting diode — LED Lesson developed RP2040 · CircuitPython · EDU PICO
LEDs turn electrical energy into light. This lesson begins with a simple LED, then explores the five addressable RGB LEDs built into the EDU PICO.
2.5.1 LED definition and operationLight-emitting diode (LED): a diode that emits light when current flows through it in the forward direction.
A conventional LED has two terminals: the anode connects toward the positive side, and the cathode connects toward the lower-voltage side. The LED must be connected with the correct polarity. A series resistor limits current and protects the LED and GPIO circuit.
For an illustrative small red LED driven from 3.3 V, suppose its forward voltage is about 2.0 V and the design target is 5 mA:
This is an example calculation, not a universal LED specification. Actual forward voltage varies by LED and current must stay within the limits of both the LED and its driver. The series-resistor arrangement was shown in Subtopic 2.4.3.
Worked examples — LED series resistor Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Vsupply supply voltage (V) VF LED forward voltage (V) I current (A) R resistance (Ω) Example 1 — Find the LED series resistance given a 3.3 V supply, 2.0 V forward voltage and 5 mA target current Given: Supply 3.3 V; LED forward voltage 2.0 V; target current 5 mA.
I = 0.005 A R = (Vsupply − VF ) ÷ I R = (3.3 V − 2.0 V) ÷ 0.005 A R = 260 Ω
Interpretation: This is an illustrative bare-LED calculation. Use a suitable standard resistor and respect the device and GPIO ratings.
Example 2 — Find the LED current with a 330 Ω resistor, 3.3 V supply and 2.0 V forward voltage Given: Same supply and LED; selected resistor 330 Ω.
I = (Vsupply − VF ) ÷ R I = (3.3 V − 2.0 V) ÷ 330 Ω I ≈ 0.00394 A I ≈ 3.94 mA
Interpretation: The larger resistance reduces the current. This is not a resistor calculation for the internally controlled WS2812 pixels.
2.5.2 The EDU PICO addressable RGB LEDsRGB LED: an LED package that combines red, green, and blue light sources so that different colour mixtures can be produced.
Addressable LED: an LED with a built-in controller that receives digital colour data, allowing software to set its colour individually or as part of a strip.
The EDU PICO has five WS2812 RGB LEDs connected to GP14 . Each pixel contains its own controller. CircuitPython sends the colour data through the NeoPixel library; GP14 is therefore a data signal for the pixel chain, not five separate ordinary LED outputs. The onboard LEDs already include their required control circuitry.
Connection schematic: GP14 sends serial data to the first pixel. Each pixel’s data output feeds the next pixel’s data input; all five share the board’s LED supply and ground.
Figure 2.3. EDU PICO five-pixel connection schematic supplied with the course materials. GP14 connects to DIN of Pixel 0; each pixel’s DOUT feeds the next pixel’s DIN. The drawing shows VDD connected to 3.3 V and VSS to common GND. For a separate WS2812-family component, confirm its exact supply requirements from that part’s datasheet before wiring.
Figure 2.4. WS2812B 5050 package drawing and pin configuration. The “5” marks the package dimension (5 mm), not a fifth pin. Image supplied with the course materials; pin functions cross-checked against the WS2812B datasheet .WS2812B package pin descriptions Pin Name Purpose and connection 1 VDD Positive supply for the LED and its built-in controller. Use the supply specified for the particular WS2812B version and board; do not infer the EDU PICO rail voltage from this package drawing. 2 DOUT Serial data output. It forwards the remaining pixel data to the next WS2812B’s DIN. The final pixel’s DOUT is normally left unconnected. 3 VSS Ground (0 V) reference. Connect it to the common ground shared by the controller and LED supply. 4 DIN Serial data input from the RP2040 or the previous pixel. The first EDU PICO pixel receives data from GP14; each pixel uses its built-in controller to pass remaining data onward.
2.5.3 Control the pixels with CircuitPythonNeoPixel object: a software object representing a chain of addressable RGB pixels and providing operations to set their colours.
This initialization creates the pixels object used by the following code to set colours and update the EDU PICO’s onboard RGB LEDs. Each constructor argument is explained in the table below.
import board
import neopixel
pixels = neopixel.NeoPixel(
board.GP14, 5,
brightness=0.1,
auto_write=False,
pixel_order=neopixel.GRB,
)
pixels.fill((255, 0, 0)) # all pixels red
pixels.show() # send the colour dataRead the constructor arguments as the hardware and behaviour settings for the pixel chain:
Meaning of the NeoPixel() arguments Argument Meaning in this example board.GP14The RP2040 GPIO pin used for the one-wire data signal. EDU PICO connects its five onboard RGB pixels to GP14. 5The number of addressable pixels in the chain. The library uses indexes 0 to 4. brightness=0.1A software brightness scale from 0.0 to 1.0. Here 0.1 requests about 10% brightness by scaling the colour values; it does not alter the RGB tuple supplied by the program. auto_write=FalseDo not send each colour change immediately. The program updates the pixel buffer first, then sends the changes when it calls pixels.show(). This is useful when updating multiple pixels together. pixel_order=neopixel.GRBTell the library the channel order expected by these LEDs: green, red, then blue in the transmitted data. In CircuitPython code, colours are still written as RGB tuples, such as (255, 0, 0) for red.
An RGB tuple is written as (red, green, blue), with each channel from 0 to 255. pixels.fill(colour) assigns one colour to every pixel.pixels[0] = colour assigns a colour to the first pixel only; indexes begin at 0.pixels.show() updates the physical strip when automatic writing is disabled.(0, 0, 0) means all colour channels are off. Set the strip dark before releasing it.
2.5.4 Explore colour, brightness, and pixel selectionAdjust the colour channels and brightness, or choose a preset. Select whether to colour all five pixels or only pixel 0. This is a browser simulation; it changes the illustration and code, not a connected board.
Interactive five-pixel RGB LED strip Five WS2812 pixels are labelled with their CircuitPython indexes, 0 through 4. They display the selected colour and brightness. Pixel 0 Pixel 1 Pixel 2 Pixel 3 Pixel 4 RGB (0, 160, 40) · brightness 25% · all five pixels
Corresponding CircuitPython: pixels = neopixel.NeoPixel(board.GP14, 5, brightness=0.25,
auto_write=False, pixel_order=neopixel.GRB)
pixels.fill((0, 160, 40))
pixels.show()Figure 2.5. Interactive RGB control simulation: the five indexed pixels and generated CircuitPython code respond to the selected colour, brightness, and pixel mode.
2.5.5 Run a colour sequence and clear the stripThe EDU PICO lesson cycles through red, green, and blue. It then clears the strip and lights only pixel 0 at a dim white colour.
for colour in ((255, 0, 0), (0, 255, 0), (0, 0, 255)):
pixels.fill(colour)
pixels.show()
time.sleep(0.5)
pixels.fill((0, 0, 0))
pixels[0] = (30, 30, 30)
pixels.show()With auto_write=False, the assignments change the software buffer first. show() sends the updated buffer to the pixels. A short delay makes each colour visible before the next update.
Step through the RGB sequence Press Next step to follow what the code does. Watch how fill() changes the software buffer, while show() sends that buffer to the LEDs.
Ready. The five pixels are OFF. Press “Next step” to begin.
Pixel 0 Pixel 1 Pixel 2 Pixel 3 Pixel 4 Software buffer: OFF for all pixels
Next step Restart Step 0 of 12
for colour in ((255, 0, 0), (0, 255, 0), (0, 0, 255)):
pixels.fill(colour)
pixels.show()
time.sleep(0.5)
pixels.fill((0, 0, 0))
pixels[0] = (30, 30, 30)
pixels.show() When the final show() runs, Pixel 0 displays dim white and Pixels 1–4 are OFF. The white looks dim because its RGB channels are all set to 30 rather than 255.
Figure 2.6. Interactive trace of the RGB colour-sequence program, showing the highlighted code, buffered colour values, and visible state of Pixels 0–4.
2.5.6 Try it and check your understandingSet all five pixels to a colour of your choice using fill(). Clear the strip, then set only the centre pixel. Which zero-based index is the centre pixel? Explain why the EDU PICO RGB LEDs use the NeoPixel interface rather than five independent digitalio outputs. 1. What does pixels.show() do when auto_write=False?
Sends the buffered colour data to the pixels Changes the GP14 pin into an analogue input Sets the brightness to 100%
2. Which call assigns the same colour to all five pixels?
pixels.fill(colour)pixels[0] = colourpixels.show()
Key idea: the EDU PICO has five addressable RGB pixels controlled together through GP14. Set pixel colours in software, then call show() to update the strip.
Course sources: EDU PICO RGB LED example and M12: WS2812 RGB LED hardware module .
CHAPTER 2 / SUBTOPIC 2.6
2.6 Seven-segment display Lesson developed RP2040 · CircuitPython · EDU PICO · M18 TM1650
Learn how seven LED bars combine to form numerals, then apply the principles to the external TM1650 four-digit display used in practical module M18.
2.6.1 Segments form a numeralSeven-segment display: a numeric display made from seven separately controlled LED bars, labelled a–g . An optional decimal point is labelled dp .
Each numeral is a pattern of lit and unlit segments. Select a digit below to see its pattern. The letters remain visible so you can identify which LED bars make each shape.
Figure 2.7. Interactive seven-segment map. Select a numeral to illuminate its a–g pattern and toggle the optional decimal point.Common numeral patterns (segment names, not electrical bit codes) Digit Segments ON Digit Segments ON 0 a, b, c, d, e, f 5 a, c, d, f, g 1 b, c 6 a, c, d, e, f, g 2 a, b, d, e, g 7 a, b, c 3 a, b, c, d, g 8 a, b, c, d, e, f, g 4 b, c, f, g 9 a, b, c, d, f, g
A driver may use a byte or bit mask to store each pattern. Which bit represents segment a depends on that driver’s definition; therefore the table lists segment names instead of assuming a universal hexadecimal code.
2.6.2 Common-anode and common-cathode displaysCommon anode (CA): the anodes of the segment LEDs are joined. To light a segment, its other side is pulled LOW so current can flow from the positive common connection through the LED and resistor into the output driver.
Common cathode (CC): the cathodes are joined. To light a segment, its other side is driven HIGH so current flows from the output driver through the resistor and LED to the common ground connection.
Figure 2.8. Common-cathode (CC) and common-anode (CA) seven-segment displays. The diagrams compare package pin assignments and internal LED connections: CC segments share a cathode connection, while CA segments share an anode connection. Check the specific display datasheet for its pinout.These polarities are useful when learning raw segment logic. The M18 TM1650 module includes a driver, so students send display data through I²C rather than wiring each segment to an RP2040 GPIO.
2.6.3 Four digits and multiplexingMultiplexing: rapidly enabling one digit at a time while presenting that digit’s segment pattern. The sequence repeats fast enough that human vision perceives a steady four-digit value. A display driver can perform this scanning without the microcontroller manually toggling every digit.
The TM1650 is the driver for the M18 external module. The four-digit module is an extension component, not a display built onto the EDU PICO. The driver handles segment patterns, digit selection, scanning, and brightness; the RP2040 sends values and commands over I²C.
2.6.4 Connect the M18 TM1650 moduleFigure 2.9. TM1650 four-digit display circuit schematic. The EDU PICO I²C lines connect GPIO5 to SCL and GPIO4 to SDA; the TM1650 digit-select and segment outputs connect to the LED module. The drawing shows 3.3 V and GND supply connections.M18 display module connection Module signal EDU PICO connection Purpose SDA GP4 · I²C data Transfers commands and display data SCL GP5 · I²C clock Times I²C communication VCC / GND 3V3 / GND via I²C Grove connection Power and common reference; confirm the module labels
Hardware note: The M18 TM1650 display is an external project module and is not pictured as a built-in EDU PICO device in the supplied Booklet V2.0. Match connector polarity and labels before powering the module.
2.6.5 Write a four-digit counter in CircuitPythonInstall the course TM1650Display library first, then use the short counter program below. The driver handles I²C locking, segment patterns and brightness; the main program handles counting and timing.
Copy TM1650Display.py into the existing CIRCUITPY/edu_pico_lib/ folder, keeping the other EDU PICO files. Use the exact import shown below: it imports the class from its module. The class is not included in the original board library.
If ImportError reports edu_pico_lib.TM1650Display, check that CIRCUITPY/edu_pico_lib/TM1650Display.py exists and its filename matches exactly. Then stop the current program in Thonny and rerun the full listing using the CircuitPython interpreter.
"""Topic 2.6.5: install edu_pico_lib/TM1650Display.py before running."""
import time
import board
import busio
from edu_pico_lib.TM1650Display import TM1650Display
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
display = None
count = 0
try:
display = TM1650Display(i2c, brightness=3)
while True:
text = "{:04d}".format(count)
display.show(text)
count = (count + 1) % 10000
time.sleep(0.1)
finally:
try:
if display is not None:
display.off()
finally:
i2c.deinit()
What the main display operations do Code Effect TM1650Display(i2c, brightness=3)Creates the display driver, clears the digits and enables output at brightness level 3 (valid levels: 1–7). "{:04d}".format(count)Formats the count as four decimal digits with leading zeros. display.show(text)Sends the four-character value to the display; also enables output if it was turned off. (count + 1) % 10000Increments the count and wraps 9999 back to 0000. display.off()Disables display output during cleanup. display.set_brightness(5)Changes the brightness to level 5. display.clear()Blanks all four digits without releasing the shared bus.
The caller creates and releases the shared I²C bus. display.off() disables the display without releasing the bus; the nested finally block ensures i2c.deinit() runs even if display cleanup fails.
See the M18 display listing in this lecture .
2.6.6 Explore number formatting and wraparoundEnter a value or use the counter controls. The simulation formats the value as four digits and updates the seven-segment model. Step from 9999 once to see the wrap back to 0000.
Figure 2.10. Interactive TM1650-style four-digit display simulation. Enter or increment a number to observe zero-padding, individual segment patterns, and 9999-to-0000 wraparound.This browser model demonstrates formatting and segment combinations; it does not communicate with a physical TM1650 module.
2.6.7 Practise and check your understandingWrite the segment names that must be ON to display digit 4. Explain why a common-anode segment typically turns ON with a LOW output, while a common-cathode segment turns ON with a HIGH output. What is the purpose of multiplexing four digits? What does "{:04d}".format(25) produce? Starting at 9998, list the next three displayed values when the counter uses (count + 1) % 10000. 1. Which segments make the numeral 1?
a and b b and c f and g
2. What does "{:04d}".format(7) return?
7 0007 7000
3. How does the M18 RP2040 send display data to the TM1650?
Seven separate GPIO outputs, one per segment I²C over SDA GP4 and SCL GP5 An analogue input
4. What follows 9999 when (count + 1) % 10000 is used?
0000 10000 9998
Key idea: seven named LED segments form each numeral. In M18, the RP2040 sends a formatted four-digit string over I²C to an external TM1650 driver, which handles segment control and digit scanning.
Course reference: M18 · TM1650 four-digit display and CircuitPython example .
Six-question MCQ check — 2.6 Seven-segment display Assessment alignment: These MCQs check CLO1 concepts (syllabus level C4), using a Bloom-level progression from prerequisite understanding and application to analysis. They prepare students for CLO2 but do not assess its P4 practical competency. After Chapter 5, integrated laboratory tasks will assess students’ ability to write programs and operate input/output hardware across the five chapters. CLO3 product proposal will be assessed separately.
1. Which segments form the familiar digit “0” on a seven-segment display? Course outcome: CLO1 · Bloom level: Understand
a, b, c, d, e, f a, b, c, d, e, f, g b, c, f, g a, d, g only
2. What changes between common-anode and common-cathode displays? Course outcome: CLO1 · Bloom level: Analyze
The shared LED connection and the polarity needed to light segments The number of segments The display becomes an OLED The segment letters change
3. What is the purpose of the decimal-point segment? Course outcome: CLO1 · Bloom level: Understand
To show a decimal point when its segment is enabled To choose the digit position To set display brightness only To communicate over I²C
4. Why does a multi-digit display often enable digits one at a time rapidly? Course outcome: CLO1 · Bloom level: Apply
Multiplexing shares segment lines across digit positions It raises the GPIO voltage It removes the need for segment patterns It converts the display into a sensor
5. In an EDU PICO display using a TM1650 controller, what does the controller simplify? Course outcome: CLO1 · Bloom level: Analyze
Display driving and digit/segment scanning RP2040 program storage Analogue voltage measurement USB enumeration
6. A digit pattern lights all outer bars but not the middle bar. Which numeral is represented? Course outcome: CLO1 · Bloom level: Evaluate
0 1 4 7
Check answers Reset Not checked yet
CHAPTER 2 / SUBTOPIC 2.7
2.7 OLED display interfacing Lesson developed RP2040 · CircuitPython · EDU PICO · I²C OLED
Connect a small graphical display to the microcontroller, place text and values on its pixel grid, and update the screen as a program runs.
2.7.1 What is an OLED display?OLED (organic light-emitting diode) display: a display whose pixels emit their own light when driven. A monochrome 128 × 64 OLED has 128 columns and 64 rows of individually addressable pixels, so it can show text, icons, and simple graphics without a backlight.
Pixel: the smallest controllable point on the screen. Pixel coordinates begin at the top-left corner: (0, 0). The rightmost column is x = 127 and the bottom row is y = 63. In the course example, the OLED is a 128 × 64 I²C display at address 0x3C; match the actual module's address and resolution.
2.7.2 I²C connection: two signal linesI²C (Inter-Integrated Circuit): a synchronous serial bus that lets a controller communicate with one or more addressed devices using a clock line and a data line. In the EDU PICO course example, SDA uses GP4 and SCL uses GP5, shared with other I²C devices on the same bus. Each device is selected by its address.
Figure 2.11. Supplied SSD1306 OLED schematic showing the display power, ground, SCL, SDA, and 4.7 kΩ pull-up resistors. Important: the supplied drawing labels GP4 as SCL and GP5 as SDA, while the course starter file uses GP5 as SCL and GP4 as SDA (SCL is the first argument in busio.I2C). These pin labels conflict; verify and correct the diagram or code against the actual EDU PICO wiring before students connect the display.Bus sharing: the OLED, AHT20, APDS9960, and TM1650 can share GP4/GP5 when each device has a distinct I²C address. Avoid creating a second I²C object for devices already connected to the same physical bus.
2.7.3 Initialize the displayThis example uses the straightforward adafruit_ssd1306 driver. It creates the I²C bus, connects the SSD1306 display, writes two lines, and sends them to the screen. Install a CircuitPython-compatible adafruit_ssd1306 library in CIRCUITPY/lib.
import board
import busio
import adafruit_ssd1306
import time
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
oled.fill(0)
oled.text("Hello EDI4153", 16, 8, 1, size=1)
oled.show()Four steps to display text Step What it does Import libraries board identifies RP2040 pins, busio creates the I²C bus, adafruit_ssd1306 controls the OLED, and time is available for timed examples.Create the I²C bus busio.I2C(board.GP5, board.GP4) uses GP5 for SCL (clock) and GP4 for SDA (data).Create the display object SSD1306_I2C(128, 64, i2c) sets the OLED size and connects it to the bus.Draw and send text fill(0) clears the image buffer, text(...) draws text, and show() transfers the buffer to the OLED. The fourth text argument is the pixel value (1 = on). Use the named size=2 argument to double the built-in font.
Positioning: text starts at the supplied top-left x/y coordinate. The default font is 5 × 8 pixels; size=2 draws it twice as large, and \n starts a new line. Keep the text within the 128 × 64 pixel screen.
2.7.4 Place text using coordinatesCoordinate: a pair of pixel values that identifies a position. In this driver, x is the left edge of the first character and y is the top edge of the text. The default font is 5 × 8 pixels; size=2 doubles its width and height. Long lines can run beyond the screen edge, so leave room for text width.
Figure 2.12. Interactive 128 × 64 pixel-coordinate preview. Change text, X position (0–128 px), Y position (0–64 px), or counter and observe how layout changes. The endpoint values mark the display edges; the last addressable pixel coordinates are x=127 and y=63. The white square overlaps the top-left corner of the first message character. In this example, the y coordinate is the top edge of the text. The preview does not communicate with a physical display.
2.7.5 Update text with live dataUpdate the screen inside a loop by clearing the buffer, drawing the complete multiline message with one oled.text() call, and calling show(). The example below displays a changing count.
count = 0
while True:
oled.fill(0)
oled.text("EDI4153\nCount: {}\nStatus: READY".format(count), 0, 0, 1, size=1)
oled.show()
count += 1
time.sleep(1)How this expression works: \n starts a new line, and "EDI4153\nCount: {}\nStatus: READY".format(count) inserts the current count into the message. fill(0) clears the previous frame before drawing, and show() updates the physical screen.
EDI4153
Count: 3
Status: READY
Figure 2.13. Example OLED output for subsection 2.7.5. The three lines represent the changing text drawn into the OLED buffer; the count shown is a sample display state.
2.7.6 Worked application: display a sensor readingSuppose an ADC has already been configured as pot. Convert its 16-bit reading to voltage, then draw both values on the OLED using the same oled object initialized in 2.7.3. This assumes the RP2040's nominal 3.3 V ADC reference; real readings can vary with supply and calibration.
# pot = analogio.AnalogIn(board.GP28) # configure earlier
while True:
voltage = pot.value * 3.3 / 65535
oled.fill(0)
oled.text("ADC: {}\nVoltage: {:.2f} V".format(
pot.value, voltage), 0, 16, 1, size=1)
oled.show()
time.sleep(0.2)Why this .format() has two arguments: the first {} is replaced by pot.value. The second placeholder {:.2f} formats voltage with two digits after the decimal point; for example, 1.65. The comma separates the two arguments, which fill the placeholders from left to right. The text is drawn into the OLED buffer, and show() sends it to the display.
If pot.value is removed from .format(): the string still contains two placeholders, but .format(voltage) supplies only one value. That value fills the first {}, and Python raises an IndexError when it looks for a second value for {:.2f}. If only voltage is needed, remove the ADC placeholder too: oled.text("Voltage: {:.2f} V".format(voltage), 0, 16, 1, size=1).
Technique: join separate lines inside one oled.text() call When each display line is easier to prepare separately, put the strings in a tuple and join them with "\n". The result is still one multiline string passed to oled.text().
lines = (
"ADC: {}".format(pot.value),
"Voltage: {:.2f} V".format(voltage),
)
oled.text("\n".join(lines), 0, 16, 1, size=1)Here, "\n".join(lines) places the voltage on the next OLED row. This is an alternative way to build the message; the 2.7.6 worked example above remains unchanged.
The display's built-in text begins at the supplied top-left x/y position. Clear the previous buffer, draw the new reading, and call show() inside the loop so each measurement appears on screen.
ADC: 32768
Voltage: 1.65 V
Figure 2.14. Example OLED output for subsection 2.7.6. An ADC reading of 32768 corresponds to approximately 1.65 V when using the nominal 3.3 V reference.2.7.7 Common problems and checksOLED troubleshooting guide Symptom Check ImportError for the SSD1306 driver Install a CircuitPython-compatible adafruit_ssd1306 library and its required dependencies in CIRCUITPY/lib; avoid mixing versions. I²C scan does not find 0x3C Check power, ground, SDA/SCL wiring, selected pins, and the display's actual address. Display stays blank Read the Thonny Shell traceback; verify OLED dimensions, I²C bus, driver, and that show() is called after drawing. Text is clipped Reduce message length or x/y position; keep the text within the 128 × 64 pixel area. Display setup fails after rerun Check the Shell traceback and wiring, then restart the program or soft-reboot the board before creating the I²C bus again.
2.7.8 Quick check: OLED interfacingChoose one answer for each question. Feedback appears after you select an option.
1. What does SSD1306_I2C(128, 64, i2c) do?
It scans the I²C bus for devices It creates a 128 × 64 OLED driver on the I²C bus It converts a number to voltage
2. In oled.text(text, x, y, 1), what does y specify?
The top edge of the text in pixels The OLED I²C address The number of display rows
3. In oled.text(text, x, y, 1), what does the fourth argument do?
It sets the display brightness level It sets the font size It turns the text pixels on
4. What happens if a two-placeholder string calls .format(voltage)?
The same value automatically fills both fields An IndexError occurs because an argument is missing The second placeholder is silently ignored
5. What makes newly drawn text visible on the OLED?
Call oled.show() after drawing Call time.sleep(1) Create a separate I²C bus for each line
6. Which expression estimates voltage from a 16-bit ADC reading?
pot.value * 65535 / 3.3pot.value + 3.3pot.value * 3.3 / 65535
2.7.9 Practice tasksInitialize the OLED at 0x3C and display your name on the first line. Display a counter that increases once per second; add Status: READY. Read GP28 and show the raw ADC value and approximate voltage, updating five times per second. Move the text to x=24, y=42. Explain why a long sentence may be clipped. Key idea: I²C carries data to the OLED; the framebuffer driver draws text into a pixel buffer, and show() sends that buffer to the screen.
CHAPTER 2 / SUBTOPIC 2.8
2.8 Pulse-width modulation — PWM Lesson developed RP2040 · CircuitPython · EDU PICO
Use fast digital pulses to control the average power delivered to a load, and use pulse frequency to set the repetition rate or tone pitch.
2.8.1 What is PWM?Pulse-width modulation (PWM): a method of controlling an output by switching a digital signal between LOW and HIGH at a regular rate, while changing how long it stays HIGH during each cycle.
A PWM pin still outputs digital voltage levels (approximately 0 V and 3.3 V on RP2040 GPIO). PWM does not directly create a continuously variable analogue voltage. Many loads respond to the average power: an LED appears dimmer or brighter, while a motor driver supplies shorter or longer power pulses to a motor.
2.8.2 Period, frequency, and duty cyclePeriod (T ): the time for one complete PWM cycle. Frequency (f ): the number of complete cycles per second, measured in hertz (Hz). Duty cycle: the percentage of each period that the signal is HIGH.
At 200 Hz and 40% duty, the period is 5 ms: HIGH lasts 2 ms and LOW lasts 3 ms. Follow the separate calculation steps in the worked examples below.
Worked examples — period and duty Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
f frequency (Hz, cycles per second) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) d duty ratio, from 0 to 1 (dimensionless) TON HIGH time within one period (same time unit as T) TOFF LOW time within one period (same time unit as T) Example 1 — Find the period, TON and TOFF at 200 Hz given a 40% duty cycle Given: Frequency 200 Hz; duty 40%.
T = 1 ÷ f T = 1 ÷ 200 Hz T = 5000 µs d = p ÷ 100 d = 40 ÷ 100 d = 0.4 TON = d × T TON = 0.4 × 5000 µs TON = 2000 µs TOFF = T − TON TOFF = 5000 µs − 2000 µs TOFF = 3000 µs
Interpretation: The HIGH and LOW times add to 5000 µs. Duty describes timing; motor speed is not guaranteed to be the same percentage.
Example 2 — Find the period, TON and TOFF at 1 kHz given a 25% duty cycle Given: Frequency 1,000 Hz; duty 25%.
T = 1 ÷ f T = 1 ÷ 1,000 Hz T = 1000 µs d = p ÷ 100 d = 25 ÷ 100 d = 0.25 TON = d × T TON = 0.25 × 1000 µs TON = 250 µs TOFF = T − TON TOFF = 1000 µs − 250 µs TOFF = 750 µs
Interpretation: The HIGH and LOW times add to 1000 µs. Duty describes timing; motor speed is not guaranteed to be the same percentage.
2.8.3 Explore the waveform and outputChange the frequency and duty cycle. The graph shows the digital HIGH/LOW signal; the LED preview changes brightness with duty cycle, and the motor indicator shows the PWM drive command qualitatively. Click Play selected tone to hear frequency control buzzer pitch; the course buzzer example steps through 440, 523, and 659 Hz. A real motor's speed also depends on its driver, supply, mechanical load, and friction.
Interactive PWM waveform A square wave changes its pulse width with duty cycle and its number of cycles in the displayed time window with frequency. HIGH LOW Time window: 20 ms 0 1 PWM cycle shown in a 20 ms window.
Figure 2.15. Interactive PWM example. Duty cycle changes the HIGH portion of each pulse; frequency changes the period and number of cycles within the fixed 20 ms graph window. LED brightness and motor drive are conceptual previews; the browser-generated tone demonstrates the pitch effect, not the physical buzzer sound.
2.8.4 Generate PWM with CircuitPythonpwmio.PWMOut(...): creates a hardware PWM output object. Its frequency is specified in cycles per second (Hz); its duty_cycle is an integer from 0 (always LOW) to 65535 (always HIGH), giving 16-bit duty setting resolution.
import board
import pwmio
# External LED with a current-limiting resistor on GP15
led_pwm = pwmio.PWMOut(
board.GP15,
frequency=1000,
duty_cycle=0,
)
try:
# Set approximately 35% duty
led_pwm.duty_cycle = int(0.35 * 65535)
finally:
led_pwm.duty_cycle = 0
led_pwm.deinit()Parameters and properties in PWMOut Item Meaning board.GP15The GPIO pin that outputs the PWM waveform. Use a pin that is free in the circuit and valid for PWM. frequency=1000Sets the repetition rate to 1000 cycles per second (1 kHz). Some loads need a different frequency; follow their driver or device requirements. duty_cycle=0Starts with the signal LOW. CircuitPython uses a 16-bit value, 0–65535. led_pwm.duty_cycle = ...Changes the fraction of each period for which the output is HIGH. Convert a percentage with int(percent / 100 × 65535). deinit()Releases the PWM hardware resource when the program is finished.
On RP2040, PWM frequency is produced by a hardware counter and clock divider. The achievable settings depend on the divider and TOP count; the clock-to-frequency calculation and detailed limits are covered in subsection 1.2. The frequencies below are examples from the course's buzzer, motor, and servo materials.
2.8.5 Map a percentage to the 16-bit settingTo convert a requested duty percentage into CircuitPython's 0–65535 range, use:
Example duty-cycle settings (rounded down to integer) Duty PWM value Interpretation 0% 0 Always LOW; output is off. 25% 16383 HIGH for one quarter of each cycle. 50% 32767 HIGH and LOW durations are approximately equal. 75% 49151 HIGH for three quarters of each cycle. 100% 65535 Always HIGH; no repeating LOW pulse.
For 35% duty, the program requests the integer duty setting 22,937. The worked examples below show the percentage conversion and explain why int() discards the fractional part.
Worked examples — duty percentage to API value Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
p percentage on a 0–100 scale (%) u integer CircuitPython duty setting, from 0 to 65,535 Example 1 — Find the 16-bit PWM duty setting for 35% duty using int() truncation Given: Duty percentage 35; use truncation to match int() in the program.
u = floor[(p ÷ 100) × 65,535] u = floor[(35 ÷ 100) × 65,535] u = floor(22,937.25) u = 22,937
Interpretation: For a non-negative value, int() discards the fractional part. floor means round down.
Example 2 — Find the 16-bit PWM duty setting for 60% duty using int() truncation Given: Duty percentage 60.
u = floor[(p ÷ 100) × 65,535] u = floor[0.60 × 65,535] u = 39,321
Interpretation: This sets duty only; frequency is configured separately.
2.8.6 PWM applications in the courseHow frequency and duty are used by EDU PICO examples Application Course example What frequency controls What duty or command controls Buzzer · GP21 03_buzzer.pyFrequency sets tone pitch (e.g. 440 Hz). 50% duty makes an audible square-wave tone; duty 0 silences it. DC motor driver · GP10/GP11 06_dc_motor.pyCourse PWM outputs use 10 kHz. DCMotor.throttle sets the drive command from −1.0 to +1.0; the library controls paired PWM outputs and direction.Servo · GP6 07_servo.py50 Hz gives a 20 ms frame period. Pulse width (set through the servo library and its angle value) represents target position; this is not the same as using duty to set LED brightness.
Important hardware distinction: use a suitable driver for motors and servos; never power them directly from a GPIO. For an external LED, include a series current-limiting resistor. EDU PICO's WS2812 pixels use their addressable-pixel protocol, not ordinary PWM pins.
2.8.7 Mini calculation tutorialA PWM signal has frequency 500 Hz and duty 30%. Calculate its period, HIGH time, and LOW time.Check: T = 1/500 = 2 ms; TON = 0.30 × 2 = 0.6 ms; TOFF = 1.4 ms. Convert 60% duty to a CircuitPython setting.Check: int(0.60 × 65535) = 39321. A 50 Hz servo signal has a 20 ms period. If its pulse is 1.5 ms, what is duty cycle?Check: (1.5/20) × 100 = 7.5%. Servo position is determined by pulse width, not by treating the servo as an LED dimmer. Key idea: frequency sets how often PWM pulses repeat; duty cycle sets the fraction of each cycle spent HIGH. CircuitPython represents duty with 16-bit values, while the load and driver determine how that pulse train becomes light, sound, or motion.
CHAPTER 2 / SUBTOPIC 2.9
2.9 Buzzer Lesson developed RP2040 · CircuitPython · EDU PICO
Use a changing electrical signal to make a passive piezo buzzer vibrate. The signal frequency sets the pitch; how long it is applied sets the note duration.
2.9.1 Buzzer and piezoelectric soundBuzzer: an output device that converts an electrical signal into an audible sound.
Piezoelectric buzzer: a sounder that uses a piezoelectric element, which flexes when voltage changes across it. Rapid flexing moves nearby air and produces sound.
The EDU PICO uses a passive piezo buzzer . “Passive” means it does not contain the oscillator needed to choose a note: the microcontroller must supply a repeating signal. An active buzzer contains its own oscillator and usually makes a preset tone when powered. The EDU PICO lesson controls pitch by generating the signal in software.
Frequency controls pitch. A faster electrical vibration produces a higher-pitched tone. Frequency does not directly set loudness. Loudness also depends on the buzzer, its drive circuit, and the signal level.
2.9.2 EDU PICO buzzer connectionBefore running the buzzer example, move the board’s audio/buzzer selector downward to Method 1 (buzzer). GP21 controls the buzzer driver shown in Figure 2.7; GP20 is the separate audio output path.
Figure 2.16. EDU PICO buzzer-driver schematic. GP21 drives Q2 (BSS138) through R7 (1 kΩ); Q2 switches the buzzer’s ground return. The buzzer’s other terminal is supplied from 3.3 V, and D3 (SS14) is connected across it as shown.Figure 2.17. Booklet view for locating the EDU PICO buzzer selector. Set it to Method 1 (downward) for the GP21 buzzer circuit in Figure 2.16. Open booklet page 33 .
2.9.3 Frequency, period, duty cycle, and durationFrequency, f : the number of complete signal cycles each second, measured in hertz (Hz). The PWM frequency determines the vibration rate and therefore the pitch heard from a passive buzzer.
Period, T : the time for one complete cycle. Frequency and period are reciprocals:
Duty cycle: the percentage of each cycle that the signal remains HIGH. A 50% duty cycle is HIGH for half the period and LOW for the other half. It makes a repeating, approximately balanced drive signal for the buzzer; it is separate from note duration.
Tone duration: how long the program keeps producing the chosen tone. For example, a 440 Hz tone for 1 s still repeats at 440 cycles each second, for about 440 cycles total. A pause after the tone creates silence between beeps.
Three timing ideas in a buzzer signal Quantity What it changes Example Frequency (Hz) Pitch of the tone 440 Hz sounds lower than 880 Hz Duty cycle (%) Fraction of each cycle that is HIGH 50%: equal HIGH and LOW portions Duration (s) Length of a note or beep 1 s tone followed by 2 s silence
In CircuitPython’s pwmio.PWMOut, duty_cycle ranges from 0 to 65535. A value of 32768 is approximately 50%; 0 holds the output LOW and produces silence. We study PWM generation and limits more fully in Subtopic 2.9.
Worked examples — buzzer timing Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
f frequency (Hz, cycles per second) T period of one cycle (s unless another time unit is stated) d duty ratio, from 0 to 1 (dimensionless) TON HIGH time within one period (same time unit as T) Example 1 — Find the period of a buzzer signal given a frequency of 440 Hz Given: Frequency 440 Hz.
T = 1 ÷ f T = 1 ÷ 440 Hz T ≈ 0.002273 s T ≈ 2.273 ms
Interpretation: The period is one waveform cycle, not the total note duration.
Example 2 — Find the period and TON of a 1 kHz buzzer signal given 50% duty Given: Frequency 1000 Hz; duty ratio 0.5.
T = 1 ÷ 1000 Hz T = 1 ms TON = d × T TON = 0.5 × 1 ms TON = 0.5 ms
Interpretation: A 0.2 s note contains 200 cycles at this frequency.
2.9.4 Generate a tone with simpleio.tone()simpleio.tone(pin, frequency, duration): a helper function that produces a tone at the chosen pin and frequency for the specified number of seconds. It is convenient for a single tone or simple beep.
import board
import simpleio
buzzer_pin = board.GP21
simpleio.tone(buzzer_pin, 440, 1) # A4 tone for 1 second
simpleio.tone(buzzer_pin, 0, 2) # silence for 2 secondsThe EDU PICO booklet uses this style: the first call sounds a 440 Hz tone for one second; a 0 Hz call represents silence for two seconds. The program then repeats these calls if they are placed inside a loop. The GP21 selector must be set to the buzzer route.
2.9.5 Change pitch with pwmio.PWMOutpwmio.PWMOut: a CircuitPython object that produces a PWM signal on a microcontroller pin. Here we set frequency and duty cycle directly, then change frequency to play different notes.
import board
import pwmio
import time
buzzer = pwmio.PWMOut(
board.GP21,
frequency=440,
duty_cycle=0,
variable_frequency=True,
)
try:
for frequency in (440, 523, 659, 523):
buzzer.frequency = frequency # change pitch
buzzer.duty_cycle = 32768 # about 50%: sound ON
time.sleep(0.25) # note lasts 0.25 s
buzzer.duty_cycle = 0 # sound OFF
time.sleep(0.15) # 0.15 s gap
finally:
buzzer.deinit() # release the PWM resourceThe values inside PWMOut(...) configure the PWM output when the buzzer object is created. The first argument is positional; the remaining settings are named parameters:
Meaning of the pwmio.PWMOut() parameters Parameter Meaning in this example board.GP21The RP2040 GPIO pin that outputs the PWM signal to the EDU PICO passive buzzer. frequency=440Set the initial PWM frequency to 440 cycles per second (440 Hz), approximately musical note A4. Later loop assignments change this frequency to play other pitches. duty_cycle=0Start with the output LOW (0% duty cycle), so the buzzer is silent until the program sets a non-zero value. variable_frequency=TrueAllow the program to change the PWM frequency after creation. The melody loop assigns new frequencies to buzzer.frequency; this option enables that retuning.
variable_frequency=True allows the PWM frequency to be changed while the object is in use. The try/finally structure ensures the PWM resource is released when the program exits the loop or is interrupted. deinit() belongs here to the PWMOut object; it is not a NeoPixel operation.
2.9.6 Explore buzzer frequencySelect a frequency, inspect the 10 ms PWM window, then press the button to hear a brief browser-generated preview. The browser sound is a learning simulation; it does not operate the physical EDU PICO buzzer. A real board needs the GP21 connection and the selector in the buzzer position.
PWM waveform for the selected buzzer frequency A 50 percent duty cycle square wave in a fixed 10 millisecond window. Frequency changes the number of cycles in the window. HIGH LOW time → · fixed 10 ms window · 50% duty Figure 2.18. Interactive 50% duty-cycle PWM waveform in a fixed 10 ms window; selecting a frequency changes the number of cycles and the browser-generated tone preview.
The graph shows signal timing, not acoustic loudness. Raising frequency puts more cycles into the same time window and raises pitch. More PWM detail is covered in Subtopic 2.9.
2.9.7 Practise and check your understandingCalculate the period of a 1 kHz buzzer signal. A 440 Hz tone is played for 0.5 s. Approximately how many signal cycles are generated? Explain why the duty cycle is not the same quantity as tone duration. Write two beeps at different pitches with a short silent gap between them. 1. Which setting primarily changes the pitch of a passive buzzer?
Tone duration PWM frequency GPIO number alone
2. What is the period of a 500 Hz signal?
2 ms 0.5 ms 500 ms
3. In the PWM example, what does setting duty_cycle = 0 do?
Holds the signal LOW to make silence Raises the pitch Sets the note to 0.5 seconds
Key idea: GP21 drives the EDU PICO passive buzzer. PWM frequency sets pitch, tone duration sets how long it sounds, and setting duty cycle to zero creates silence.
Course references: EDU PICO Booklet V2.0, pp. 33–35 ; course GP21 buzzer example ; M13: Audio and buzzer hardware module .
CHAPTER 2 / SUBTOPIC 2.10
2.10 DC motor Lesson developed RP2040 · CircuitPython · EDU PICO · H-bridge driver
Use the EDU PICO's motor-driver channels to set a brushed DC motor's direction and speed command without drawing motor current from an RP2040 GPIO.
2.10.1 DC motor and driverDC motor: an actuator that turns electrical energy into continuous rotational motion. Reversing the polarity across a two-wire brushed motor reverses its rotation.
H-bridge motor driver: a power-switching circuit that controls the direction of current through the motor. The RP2040 sends low-current control signals to the driver; the driver switches the separate motor-power path and handles more current than a GPIO can provide.
The EDU PICO motor-drive circuit uses the MX1515H H-bridge driver IC . The RP2040 controls its Motor 1 channel through GP10 and GP11; the course pin map assigns GP12 and GP13 to Motor 2. The motor connects to the corresponding board screw terminal. These GPIO pins carry low-current control signals; the MX1515H switches the motor current from the motor supply. Follow the board's specified supply and grounding instructions.
Why not connect a motor directly to a GPIO? Supply the motor current: a motor can draw more current—especially at startup or stall—than a 3.3 V GPIO pin is designed to provide. The MX1515H switches current from the motor supply while the GPIO provides only a control signal.Protect the controller: motor windings store magnetic energy and can create voltage transients when switched. The driver stage provides the intended switching path so these motor effects are not applied directly to the RP2040 GPIO.Control motor direction: reversing a DC motor requires reversing the polarity across its terminals. The H-bridge switches the motor-power connections to make clockwise (CW) and counterclockwise (CCW) operation possible.Control motor speed with PWM: the RP2040 can send PWM control signals to the driver. Changing the duty cycle changes the average drive applied to the motor; actual speed also depends on the motor, supply, load, and driver.Choose how the motor stops: the bridge can use different output states for coasting or braking. In the course CircuitPython motor example, throttle = None requests coast, while throttle = 0.0 requests active braking.Signal path: RP2040 GPIO (3.3 V control) → MX1515H switches motor-supply current → M1 motor terminals. Use the EDU PICO motor driver circuit and its specified supply arrangement.
Figure 2.19. EDU PICO motor-driver schematic supplied with the course materials. The schematic labels the H-bridge IC MX1515H ; GP10/GP11 control Motor 1 and GP12/GP13 control Motor 2. The 5 V motor supply powers the driver stage, while the RP2040 GPIO lines carry control signals.Course hardware reference: EDU PICO Booklet V2.0, motor-driver illustrations and instructions, pp. 12 and 124–129. Open the motor section in the booklet .
2.10.2 Direction and speed commandThrottle: the signed motor command used by adafruit_motor.motor.DCMotor. Positive values command clockwise (CW) rotation in this model, negative values command counterclockwise (CCW), and the magnitude gives the requested drive level from 0 to 1.
For example, 0.4 requests clockwise (CW) drive at 40% throttle in this model; -0.4 requests counterclockwise (CCW) drive at 40% throttle in this model. This is a drive command, not a promise that the shaft speed is exactly 40% of its maximum. Actual speed depends on motor voltage, load, friction, driver losses, and the motor itself.
Interactive MOTOR2 H-bridge control and GPIO PWM values RP2040 GP13 and GP12 provide separate PWM control signals to the MX1515H H-bridge for MOTOR2. Live labels show each GPIO PWM duty cycle. The MOTOR2 rotor display turns clockwise (CW) for positive throttle and counterclockwise (CCW) for negative throttle, viewed from the shaft end; the actual direction depends on motor wiring. MOTOR2 · MX1515H H-BRIDGE CONTROL GPIO13 PWM 40% GPIO12 PWM 0% MX1515H H-bridge M2 channel M2 CLOCKWISE (CW) Throttle magnitude GPIO duty-cycle readouts are control signals, not motor speed. PWM drive command: 40%
Figure 2.20. Interactive MOTOR2 control model. GP13 and GP12 connect to the MX1515H input pair; live PWM duty-cycle labels update for clockwise, counterclockwise, coast, and brake commands. The model uses positive throttle for CW and negative throttle for CCW as a viewing/wiring convention; actual direction depends on motor-lead orientation. It does not drive a connected motor.CW/CCW convention: The model labels positive throttle as clockwise (CW) and negative throttle as counterclockwise (CCW), viewed from the motor shaft end. The actual direction depends on motor wiring; swapping the two motor leads reverses CW and CCW.
Reading the GPIO PWM labels: With the course
adafruit_motor.motor.DCMotor example’s default fast-decay mode, positive throttle applies PWM to GP13 and sets GP12 to 0%; negative throttle applies PWM to GP12 and sets GP13 to 0%.
throttle = None sets both PWM duty cycles to 0% (controller off/coast), while
throttle = 0.0 sets both to 100% (brake). These are RP2040 control-signal duty cycles; they are not a direct measurement of motor terminal voltage or speed. See the
Adafruit DCMotor implementation .
Important difference: throttle = None turns both PWM outputs off so the motor can coast. throttle = 0.0 drives both outputs fully on, producing an active-braking state in this library. Do not treat None and numeric zero as interchangeable.
2.10.3 Create a motor object in CircuitPythonThe course file 20262027/lecture_examples/06_dc_motor.py creates two PWM outputs for Motor 1 and wraps them in a motor object. The library then applies direction and PWM settings when the program assigns throttle.
import board
import pwmio
import time
from adafruit_motor import motor
motor_a = pwmio.PWMOut(board.GP13, frequency=10000)
motor_b = pwmio.PWMOut(board.GP12, frequency=10000)
motor_1 = motor.DCMotor(motor_a, motor_b)
try:
for command in (0.4, None, -0.4, None):
motor_1.throttle = command
time.sleep(1)
finally:
motor_1.throttle = None
motor_a.deinit()
motor_b.deinit()Read the motor setup and commands Code Meaning PWMOut(GP13, frequency=10000)Creates one 10 kHz PWM control signal for the Motor 1 driver channel. PWMOut(GP12, frequency=10000)Creates the second control signal. The pair supports direction and speed control through the H-bridge. motor.DCMotor(motor_a, motor_b)Creates the library object that coordinates the two PWM outputs. throttle = 0.4Requests clockwise (CW) rotation with a 0.4 throttle magnitude in this model. throttle = -0.4Requests counterclockwise (CCW) rotation with a 0.4 throttle magnitude in this model. throttle = NoneTurns both PWM outputs fully off (coast state). deinit()Releases the two PWM resources after the motor is stopped.
2.10.4 Calculate the PWM timing in the course exampleThe course motor example requests 10,000 Hz PWM. Use the magnitude of the throttle as an approximate duty ratio in this timing model. The sign selects direction according to wiring; it does not make time negative. Driver decay mode can change the input waveforms. PWM timing alone does not determine shaft speed.
Worked examples — motor PWM timing Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
f frequency (Hz, cycles per second) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) d duty ratio, from 0 to 1 (dimensionless) TON HIGH time within one period (same time unit as T) TOFF LOW time within one period (same time unit as T) Example 1 — Find TON and TOFF at 10 kHz given a 40% duty cycle Given: Frequency 10,000 Hz; duty 40%.
T = 1 ÷ f T = 1 ÷ 10,000 Hz T = 100 µs d = p ÷ 100 d = 40 ÷ 100 d = 0.4 TON = d × T TON = 0.4 × 100 µs TON = 40 µs TOFF = T − TON TOFF = 100 µs − 40 µs TOFF = 60 µs
Interpretation: The HIGH and LOW times add to 100 µs. Duty describes timing; motor speed is not guaranteed to be the same percentage.
Example 2 — Find TON and TOFF at 10 kHz given a 75% duty cycle Given: Frequency 10,000 Hz; duty 75%.
T = 1 ÷ f T = 1 ÷ 10,000 Hz T = 100 µs d = p ÷ 100 d = 75 ÷ 100 d = 0.75 TON = d × T TON = 0.75 × 100 µs TON = 75 µs TOFF = T − TON TOFF = 100 µs − 75 µs TOFF = 25 µs
Interpretation: The HIGH and LOW times add to 100 µs. Duty describes timing; motor speed is not guaranteed to be the same percentage.
Example 3 — Find TON and TOFF at 20 kHz given a 40% duty cycle Given: Frequency 20,000 Hz; duty 40%.
T = 1 ÷ f T = 1 ÷ 20,000 Hz T = 50 µs d = p ÷ 100 d = 40 ÷ 100 d = 0.4 TON = d × T TON = 0.4 × 50 µs TON = 20 µs TOFF = T − TON TOFF = 50 µs − 20 µs TOFF = 30 µs
Interpretation: The HIGH and LOW times add to 50 µs. Duty describes timing; motor speed is not guaranteed to be the same percentage.
2.10.5 Test sequence and troubleshootingWith the motor supply switched off, check that the motor is connected to the intended M1 screw terminal and that the board's supply/common-ground instructions are followed. Run the supplied example and identify the order: clockwise (CW) 0.4, coast, counterclockwise (CCW) 0.4, coast. The actual CW direction depends on motor-lead orientation and viewing side. If the shaft turns opposite to the model's CW/CCW labels, swap the motor leads at the output terminals or swap the DCMotor input order in code. If the motor does not turn, check the driver supply, terminal connection, selected pins (GP10/GP11 for M1), library installation, and Thonny Shell errors. Compare None with 0.0. Explain why one coasts while the other brakes in this library. Hardware rule: do not connect a DC motor directly to a GPIO pin. Use the EDU PICO motor driver and the specified motor supply. Turn the supply off while changing screw-terminal wiring.
Key idea: the RP2040 creates control signals; the H-bridge switches motor current and polarity. A signed throttle value selects direction and requested drive, while PWM frequency and duty determine the switching pattern. The H-bridge keeps motor current out of the microcontroller GPIO.
References: Course file 06_dc_motor.py and EDU PICO Course notes. See the Adafruit motor library DCMotor API for the current throttle definition.
CHAPTER 2 / SUBTOPIC 2.11
2.11 Stepper motor Lesson developed RP2040 · CircuitPython · external stepper driver required
Learning outcomes Explain how sequentially energized coils produce discrete stepper-motor movement. Interpret full-step and half-step sequences and calculate ideal step count, angle, and rate. Select appropriate driver and supply connections for the course example. Course alignment: CLO1 (concepts and problem analysis). CLO2 practical skill will be assessed later through the integrated laboratory tasks planned after Chapter 5.
2.11.1 What is a stepper motor?
A stepper motor is a brushless motor that turns in discrete angular increments when its stator coils are energized in a controlled sequence. Each command advances the rotor toward a new magnetic alignment. A step count can estimate position from a known starting reference, but the motor does not necessarily report its actual position.
Stator The stationary part containing electrically energized coils. The coil sequence creates a moving magnetic field.
Rotor The rotating magnetic or toothed part that follows the changing stator field.
Step angle The nominal angle moved per commanded step. It depends on motor construction and drive mode; gearing changes the output-shaft movement.
Unipolar: course 28BYJ-48 with ULN2003 driver
Bipolar: two-phase hybrid motor cutaway showing rotor and stator
Figure 2.24. Side-by-side comparison of the course 28BYJ-48 unipolar motor and a hybrid bipolar motor . The left image shows a unipolar motor and ULN2003 driver arrangement; its GP12–GP15 labels belong to that illustrated setup, so follow Figure 2.22 and the course code for the EDU PICO GPIO connections. The right image identifies rotor and stator parts in a NEMA 17 hybrid bipolar motor; it is not the 28BYJ-48. Both images: RS DesignSpark, “Microcontroller Interfaces: Stepper Motors” .
The motor used for this topic is the 28BYJ-48 permanent-magnet stepper motor . It has a permanent-magnet rotor, four stator phases and a reduction gearbox. Its five-wire winding arrangement is unipolar : one lead is the shared winding common and the other four are phase-control leads. The gear train reduces output speed and increases available output torque, but gear backlash and variations between versions mean that the motor should not be treated as a precision absolute-position device.
Using a nominal 64:1 gearbox, the 28BYJ-48 needs about 2,048 full steps or 4,096 half-steps per output-shaft revolution. The course CircuitPython example uses stepper.INTERLEAVE (half-step), so 2,048 calls give about 180°, not 360° . See 2.11.3 for calculations. Actual motor versions and gear ratios can differ; verify or calibrate the fitted motor for accurate angles.
A stepper is commanded by the sequence and number of steps rather than a continuous signed throttle. It can hold a position while its coils remain energized, but this draws current and produces heat. If the load or step rate is too high, the rotor may fail to follow the commanded sequence and miss steps.
2.11.2 Unipolar and bipolar stepper motors
Unipolar winding: each motor phase has a centre tap (or shared common connection). The driver energizes the winding sections in sequence without reversing current through each section. In the common five-wire 28BYJ-48, the centre taps are joined internally to one common lead.
Bipolar winding: the motor has two electrically separate phases with both ends of each phase available. To reverse a phase's magnetic polarity, the driver reverses current through that winding, usually with an H-bridge for each phase.
Unipolar and bipolar stepper-motor comparison Feature Unipolar — course 28BYJ-48 Bipolar Typical winding connections Five-wire 28BYJ-48: four phase ends plus one internally shared common lead. Four wires for two separate phases; both ends of each phase are accessible. How phase polarity is changed Current is switched through selected winding sections; the simple driver does not reverse current through a phase. An H-bridge reverses current through each phase winding. Typical driver Four low-side transistor switches, such as the external ULN2003 module used by the course example. Two H-bridge channels or a dedicated bipolar stepper driver. Advantages Simpler switching circuit and straightforward four-phase sequence; well matched to the supplied 28BYJ-48 and ULN2003 driver. Can energize a complete phase winding in either direction; often provides better torque utilization from a comparable motor, depending on winding and driver. Tradeoffs Usually lower torque per motor size than a comparable bipolar drive because only part of a centre-tapped phase is used at a time; the common lead must be connected correctly. Driver and current control are more involved because each phase needs current reversal; wiring and driver choice must match the motor's phase current. Suitability for this practical Yes. The standard five-wire 28BYJ-48 is unipolar and is driven with the ULN2003-class board shown below.No, not directly. A standard five-wire 28BYJ-48 has its phase centre taps joined internally; do not treat it as an ordinary four-wire bipolar motor.
Unipolar · 28BYJ-48 Bipolar · two-phase example
Figure 2.21. Interactive comparison of unipolar and bipolar stepper-motor winding operation. In Unipolar mode, this figure uses wave drive (single-phase full-step): A → B → C → D, with one winding section energized at a time. It does not show the alternating single/paired states of half-step. Choose a winding type and step the sequence to observe the conceptual field and rotor alignment. The standard five-wire 28BYJ-48 used in this course is unipolar; see the table below and Figure 2.23 for the other unipolar drive sequences.
For the 28BYJ-48 , current flows from the shared common lead through an energized phase winding and then through the corresponding ULN2003 transistor switch to ground. Advancing through phases A, B, C, and D moves the stator field around the permanent-magnet rotor, which follows it step by step. Reversing the phase order reverses the field sequence and the rotor direction.
A bipolar motor works differently: its driver reverses current through phase A and/or phase B to swap each phase's magnetic polarity. The unipolar and bipolar labels describe winding connections and drive method; they do not mean that one motor type uses a different stepper principle.
Stepper winding labels and conceptual energizing sequences Drive type Conceptual sequence How to read it
Unipolar wave drive (single-phase full-step, 28BYJ-48) A → B → C → D → repeatOne winding section is ON in each of four states. This is the unipolar sequence shown in Figure 2.21. Wave drive is a full-step method; it is not half-step.
Unipolar two-phase full-step (28BYJ-48) AB → BC → CD → DA → repeatTwo neighboring winding sections are ON in every state: AB means A and B together. Four states per cycle. Select Full-step in Figure 2.23 to see this sequence.
Unipolar half-step (28BYJ-48) A → AB → B → BC → C → CD → D → DA → repeatOne-section and two-section states alternate. Eight states insert intermediate positions between the full-step positions, halving the commanded step angle. Torque can vary between states. This is the default Half-step mode in Figure 2.23.
Bipolar comparison (two independent phases) A+ → A−B+ → B−A+ and A− are the two ends of phase A; B+ and B− are the two ends of phase B. Reversing current direction through a phase reverses its magnetic polarity. These are not additional unipolar phases, and these arrows illustrate current reversal rather than a complete stepping sequence.
Reading the sequences: A, B, C, and D name four switchable unipolar winding sections. A means only A is energized; AB means A and B are energized together. Unipolar describes the winding connection; wave drive, two-phase full-step, and half-step describe how those same windings are switched. Figure 2.21 illustrates wave drive; Figure 2.23 compares two-phase full-step with half-step. Its four-state or eight-state cycle is a conceptual magnetic-field cycle, not one complete revolution of the geared 28BYJ-48 output shaft. Reverse the state order to reverse the illustrated direction.
Keep the labels simple: use A, B, C, D for the four conceptual unipolar sections, and A+, A−, B+, B− for the two ends of the two bipolar phases. The labels IN1–IN4 are only the printed control-input names on the ULN2003 driver; they belong in the wiring diagram and hardware/code connection details, not as another set of motor winding labels. The phase order depends on wiring and the course code's configured coil order and INTERLEAVE style. Reversing a valid sequence reverses rotation; physical CW/CCW also depends on coil order and viewing side.
Figure 2.22. EDU PICO and ULN2003 unipolar stepper-driver connection. GP26, GP27, GP8, and GP7 connect to the four driver inputs; driver outputs connect to STEPPER_COIL_A–D as labelled. The LEDs and 500 Ω resistors are channel indicators in this schematic, not the motor windings. The shown 5 V/common and ground connections must match the fitted driver and motor supply. This figure's GPIO assignments agree with 08_stepper.py. The lower line connected to ULN2003 COMMON and +5 V is the clamp-diode common connection, not a fifth phase; the supplied drawing appears to repeat the coil D label there.
Why use a ULN2003 instead of connecting the motor to GPIO?
An RP2040 GPIO is a 3.3 V logic control pin . It tells a circuit “ON” or “OFF”; it is not a motor power output. A stepper winding is a low-resistance, inductive load that needs more current than a GPIO should supply. Connecting a winding directly can overload and damage the RP2040 pin.
What each part does in this unipolar setup Part Its role RP2040 GPIO Sends a small 3.3 V control signal to one ULN2003 input; it does not carry the motor-coil current. ULN2003 Acts as a four-channel low-side switch for the four unipolar phases. When an input is active, its Darlington output sinks current from the selected winding to GND. Motor supply Provides the voltage and current for the motor windings. The motor common lead connects to the motor supply positive; driver and controller grounds need a shared reference.
Current capacity: the driver switches the coil current, keeping that load off the microcontroller GPIO.Inductive kick: a winding resists a sudden current change and can produce a voltage spike when switched off. ULN2003 devices include clamp diodes for inductive loads; the driver board’s COM connection must be wired as specified so the clamp path works.Four-phase sequencing: the ULN2003 provides separate switch channels so the program can energize phases A, B, C, and D in order.
Remember: ULN2003 is a transistor array, not an H-bridge. It switches unipolar winding sections in one current direction; it does not reverse current through a bipolar phase. Use a correctly rated driver and motor supply, and follow the actual motor/driver datasheets. See the TI ULN2003A datasheet and RP2040 datasheet .
Hardware boundary: The EDU PICO materials used here do not identify an onboard stepper motor or dedicated stepper driver. Do not connect motor coils directly to RP2040 GPIO. This example needs a compatible external driver (the course example specifies ULN2003) and a motor supply suitable for the motor. Join the controller and driver grounds so the GPIO levels have a shared reference. Check the actual module schematic; do not assume every ULN2003 board uses the same connector order.
2.11.3 Step angle, position, and rateCalculate the angle at the output shaft using the selected drive mode. In the nominal 64:1 course model, DOUBLE uses 2048 increments per revolution and INTERLEAVE uses 4096. A revolution is 360° in either mode.
Choose the mode, then the equation N number of increments per output-shaft revolution for the selected stepper mode n number of commanded increments (calls) α output-shaft angle per increment (degrees) θ requested or calculated output-shaft angle (degrees) Δt time between step commands (s) t elapsed time or duration (s unless otherwise stated) fstep commanded step rate (increments/s) s shaft speed (revolutions/minute, rpm) α = 360° ÷ N θ = n × α n = θ × N ÷ 360° t = n × Δt fstep = 1 ÷ Δt s = 60 × fstep ÷ N
28BYJ-48 nominal output-shaft calculations — assuming a 64:1 gearbox Drive mode Adafruit style Increments per 360° Output angle per increment Calls for 90° / 180° / 360°
Wave drive / two-phase full-step stepper.SINGLE / stepper.DOUBLE32 × 64 = 2,048 360° ÷ 2,048 = 0.17578125° 512 / 1,024 / 2,048
Half-step — course code stepper.INTERLEAVE64 × 64 = 4,096 360° ÷ 4,096 = 0.087890625° 1,024 / 2,048 / 4,096
The nominal internal rotor angles are 11.25° per full step and 5.625° per half-step. Gear reduction gives the smaller output-shaft angles. Actual gearbox ratios, missed steps and load affect movement; calibrate the fitted motor for accurate angles. Keep one drive mode throughout a movement to avoid an initial alignment increment.
Worked examples — step angle, position and rate Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
N number of increments per output-shaft revolution for the selected stepper mode n number of commanded increments (calls) α output-shaft angle per increment (degrees) θ requested or calculated output-shaft angle (degrees) Δt time between step commands (s) t elapsed time or duration (s unless otherwise stated) fstep commanded step rate (increments/s) s shaft speed (revolutions/minute, rpm) Example 1 — Find the step angle and calls for 135° using DOUBLE with 2048 increments per revolution Given: 2,048 increments/revolution; requested angle 135°.
α = 360° ÷ N α = 360° ÷ 2,048 α = 0.17578125° n = θ × N ÷ 360° n = 135° × 2,048 ÷ 360° n = 768
Interpretation: Use range(768) with stepper.DOUBLE. Keep that mode throughout the movement; opposite-direction movement returns approximately to the start.
Example 2 — Find the step angle and calls for 135° using INTERLEAVE with 4096 increments per revolution Given: 4,096 increments/revolution; requested angle 135°.
α = 360° ÷ N α = 360° ÷ 4,096 α = 0.087890625° n = θ × N ÷ 360° n = 135° × 4,096 ÷ 360° n = 1,536
Interpretation: Use range(1536) with stepper.INTERLEAVE. Keep that mode throughout the movement; opposite-direction movement returns approximately to the start.
Example 3 — Find the step angle and calls for 90° using DOUBLE with 2048 increments per revolution Given: 2,048 increments/revolution; requested angle 90°.
α = 360° ÷ N α = 360° ÷ 2,048 α = 0.17578125° n = θ × N ÷ 360° n = 90° × 2,048 ÷ 360° n = 512
Interpretation: Use range(512) with stepper.DOUBLE. Keep that mode throughout the movement; opposite-direction movement returns approximately to the start.
Example 4 — Find the output angle for 2048 INTERLEAVE calls given 4096 increments per revolution Given: 4096 half-steps/revolution; 2048 calls.
θ = n × 360° ÷ N θ = 2048 × 360° ÷ 4096 θ = 180°
Interpretation: A full turn needs 4096 calls in this mode.
Example 5 — Find the angle and delay-only time for 128 INTERLEAVE calls at 4096 increments per revolution and 5 ms per call Given: INTERLEAVE; 4096 increments/revolution; delay 0.005 s per call.
θ = n × 360° ÷ N θ = 128 × 360° ÷ 4096 θ = 11.25° t = n × Δt t = 128 × 0.005 s t = 0.64 s
Interpretation: Time here includes delays only; interpreter work and the pause between directions add time.
Example 6 — Find the step rate, full-turn time and rpm given 4096 increments per revolution and 5 ms per call Given: INTERLEAVE; 4096 increments; 0.005 s delay per call.
fstep = 1 ÷ Δt fstep = 1 ÷ 0.005 s fstep = 200 increments/s t = N × Δt t = 4096 × 0.005 s t = 20.48 s s = 60 × fstep ÷ N s = 60 × 200 ÷ 4096 s ≈ 2.93 rpm
Interpretation: The factor 60 converts seconds to minutes. Processing overhead reduces the achievable rate.
Example 7 — Find the angle for 75 DOUBLE calls and the delay-only time for 768 calls, given 2048 increments per revolution and 5 ms per call Given: DOUBLE; 2048 increments/revolution; 0.005 s delay per call.
θ = 75 × 360° ÷ 2048 θ ≈ 13.18° t = n × Δt t = 768 × 0.005 s t = 3.84 s
Interpretation: 75 calls do not give 135° on this geared motor. The 768-call movement has 3.84 s of delays.
2.11.4 CircuitPython example used in the course
The source example 20262027/lecture_examples/08_stepper.py creates four digital outputs and passes them to the Adafruit motor library. It uses 128 interleaved step calls in each sequence direction with a 5 ms pause between calls. The library constants stepper.FORWARD and stepper.BACKWARD mean sequence order; the resulting physical CW/CCW direction depends on coil order and motor wiring. 128 is the requested step count in that demonstration; it is not stated as one full revolution.
import board
import digitalio
import time
from adafruit_motor import stepper
# Four EDU PICO control GPIOs; see the wiring figure for connections.
control_pins = [board.GP26, board.GP27, board.GP8, board.GP7]
outputs = [digitalio.DigitalInOut(pin) for pin in control_pins]
for output in outputs:
output.switch_to_output(value=False)
# Name the four logical unipolar phase channels A, B, C, D.
# Keep the course example's coil order for this motor and library.
phase_a, phase_b, phase_c, phase_d = (
outputs[0], outputs[2], outputs[1], outputs[3]
)
motor = stepper.StepperMotor(
phase_a, phase_b, phase_c, phase_d, microsteps=None
)
try:
for direction in (stepper.FORWARD, stepper.BACKWARD):
for _ in range(128):
motor.onestep(direction=direction, style=stepper.INTERLEAVE)
time.sleep(0.005)
time.sleep(0.5)
finally:
motor.release()
for output in outputs:
output.deinit()
In this code, phase_a through phase_d are the four logical unipolar phase channels supplied to the library. The variable names are for learning and do not change the physical pin labels on a driver board. The code keeps the course example's output order; follow the wiring figure for physical connections, and remember that another motor or board may need a different order.
StepperMotor(...)Creates a motor object from four digital outputs. The order matters because it determines how the library pairs coils.
stepper.FORWARD / BACKWARDSelects the order in which the library advances through its phase sequence.
style=stepper.INTERLEAVEAlternates single- and paired-coil states for half-step interleaving: nominally 4,096 calls per output-shaft revolution for this course motor.
motor.release()De-energizes the phases after motion. The shaft may then turn more easily because holding torque is removed.
To test one nominal full turn: change range(128) in the complete program to range(4096) and retain style=stepper.INTERLEAVE. It will request about 360° in one direction, pause, then about 360° in the opposite direction. Observe the first movement before the return; the complete forward/return pair has approximately zero net displacement. At 5 ms per call, allow at least 20.48 s of delays for each turn. A range(2048) movement in this style requests about 180°. The four/eight states in Figure 2.23 represent a conceptual field cycle, not a geared output-shaft revolution.
2.11.5 Interactive coil-sequence simulator
Use the controls to inspect how a sequence changes the energized phases and ideal rotor alignment. This is a teaching model: it does not represent the exact magnetic geometry, torque, gearing, or step calibration of a particular motor.
Animated four-phase stepper motor sequence Four stator poles surround a centered rotor. Energized phases highlight as the sequence advances; the rotor indicator aligns with the resultant field. A B C D ROTOR Highlighted poles are energized in the selected state Phase output states · ON = 1, OFF = 0 A : B : C : D : 1 ON 0 OFF 0 OFF 0 OFF
Figure 2.23. Interactive conceptual unipolar phase sequence, matching the table in 2.11.2. Full-step means two-phase full-step: AB → BC → CD → DA (four states, two sections ON throughout). Half-step is the default: A → AB → B → BC → C → CD → D → DA (eight states, alternating one and two sections ON). Each step button advances or reverses one state in the selected mode. The highlighted poles and A/B/C/D readout show that state; rotor angles are conceptual, not the actual geared output-shaft step angles. Wave drive is illustrated separately in Figure 2.21.
2.11.6 Choosing and troubleshooting a stepper system
Design checks before energizing a stepper motor Check Why it matters Driver and motor compatibility The driver must match motor type, coil current, voltage, and phase arrangement. Supply and ground Use a motor supply rated for the load and a shared ground/reference as required by the driver. Coil order An incorrect order can cause vibration, weak torque, or no rotation; verify wiring from the driver/motor documentation. Step rate and load Starting too quickly or demanding excessive torque can make the motor miss steps. Position reference Open-loop step counting estimates movement from a known home position; use a limit switch or other reference when absolute position matters. Release behavior Releasing coils reduces heating but removes holding torque; consider the mechanism and load before stopping.
Design exercise: A mechanism needs to move an indexed platform by 90° using a motor specified at 1.8° per full step. Calculate the ideal number of full steps, state what can make the real angle differ, and select two hardware checks required before connecting the motor.
Six-question MCQ check — 2.11 Stepper motor Assessment alignment: These MCQs check CLO1 concepts (syllabus level C4), using a Bloom-level progression from prerequisite understanding and application to analysis. They prepare students for CLO2 but do not assess its P4 practical competency. After Chapter 5, integrated laboratory tasks will assess students’ ability to write programs and operate input/output hardware across the five chapters. CLO3 product proposal will be assessed separately.
1. How is the course 28BYJ-48 stepper motor classified? Course outcome: CLO1 · Bloom level: Understand
Four-wire bipolar hybrid stepper Brushed DC motor with an encoder Five-wire unipolar permanent-magnet stepper RC positional servo
2. Using the nominal 64:1 model, how many INTERLEAVE calls request one 360° output-shaft turn of the course 28BYJ-48? Course outcome: CLO1 · Bloom level: Apply
200 2,048 4,096 128
3. Using 2,048 full steps per revolution and stepper.DOUBLE, how many calls request a nominal 135° output-shaft movement? Course outcome: CLO1 · Bloom level: Analyze
75 384 768 1,536
4. Why does the course stepper example require an external driver? Course outcome: CLO1 · Bloom level: Analyze
GPIO pins cannot produce logic signals The driver stores CircuitPython code Stepper motors communicate only through USB The driver switches coil current beyond what a GPIO can supply
5. The course code is changed to range(2048) while retaining stepper.INTERLEAVE. Using 4,096 half-steps per revolution, what is the nominal movement in each direction? Course outcome: CLO1 · Bloom level: Analyze
360°, because 2,048 always means a full turn 90° 180°, because INTERLEAVE commands half-steps 2,048°
6. Why can an open-loop step count fail to give the mechanism’s true absolute position? Course outcome: CLO1 · Bloom level: Analyze
Because a stepper has no stator The motor may miss steps, and a reference/home position may be unknown Because a loop counter always counts backward Because the display uses I²C
Check answers Reset Not checked yet
CHAPTER 2 / SUBTOPIC 2.12
2.12 Servo motor Lesson developed EDU PICO · GP6 servo signal · GP28 potentiometer · CircuitPython
Learning outcomes By the end of this subtopic, students should be able to:
Explain how a position servo uses an internal feedback loop to move and hold its shaft. Relate PWM pulse width to a commanded servo position and calculate the frame period and duty ratio. Connect and control the EDU PICO servo output safely, then map the onboard potentiometer reading to a bounded angle. Course alignment: CLO1 concepts and application, progressing to analysis. CLO2 practical performance will be assessed later in the integrated laboratory tasks after Chapter 5.
2.12.1 What is a hobby servo?
A hobby servo is a rotary actuator that moves its output shaft toward a commanded position and uses internal feedback to reduce the difference between the requested and actual position.
A typical positional servo contains a small DC motor, reduction gears, a position-sensing potentiometer, and a control circuit. The microcontroller sends a repeated command pulse on the signal wire. The servo's internal controller compares the commanded position with its sensor reading, drives the motor in the required direction, and slows or stops it near the requested position. The RP2040 sends the command; it does not read the servo's internal position sensor in this basic connection.
Command Pulse width on the signal wire represents the requested position.
Actuation The internal motor and gears turn the servo horn.
Feedback An internal sensor reports shaft position to the servo controller.
Figure 2.25. Internal position-control mechanism of a hobby servo. The incoming PWM command is converted to a position reference; the potentiometer measures the output shaft, and the controller drives the motor until the position error is reduced. Image: Embedded Lab, servo mechanism diagram .
Figure 2.26. Internal parts of a hobby positional servo. The motor turns the gear train; the output spline moves the horn, while the potentiometer senses shaft position for the control circuit. Image: Embedded Lab, servo parts photograph .
Position servo versus continuous-rotation servo: a positional servo interprets pulse width as a target angle. A continuous-rotation servo interprets the pulse as direction and speed command, so the same angle mapping does not apply.
2.12.2 How the control pulse sets position
A common hobby-servo command repeats about 50 times per second . At 50 Hz, one frame period is:
The servo measures the short HIGH pulse in each frame. For a simple teaching example, pulses near 1.0 ms, 1.5 ms, and 2.0 ms may request positions near 0°, 90°, and 180° respectively. These values are illustrative : pulse limits and mechanical travel vary by servo, so use its specification and avoid forcing the horn against a stop.
Illustrative servo command with a 20 ms frame and a 1,000–2,000 μs range Pulse width Approximate commanded angle Duty ratio in a 20 ms frame What the servo does 1.0 ms 0° 1 ÷ 20 × 100 = 5% Moves toward one end of its calibrated travel 1.5 ms 90° 1.5 ÷ 20 × 100 = 7.5% Moves toward the midpoint 2.0 ms 180° 2 ÷ 20 × 100 = 10% Moves toward the other end of its calibrated travel
Do not confuse servo PWM with LED dimming or DC-motor speed control. For a servo, the position command is encoded mainly by pulse width; the frame repeats to maintain the command. A pulse of 1.5 ms at 50 Hz occupies 7.5% of the frame, but that percentage is not a direct “7.5% position” or speed.
Worked examples — servo pulse timing Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
f frequency (Hz, cycles per second) T period of one cycle (s unless another time unit is stated) TON HIGH time within one period (same time unit as T) d duty ratio, from 0 to 1 (dimensionless) u integer CircuitPython duty setting, from 0 to 65,535 Example 1 — Find the servo frame period given a 50 Hz control frequency Given: Servo-control frequency 50 Hz.
T = 1 ÷ f T = 1 ÷ 50 Hz T = 0.020 s T = 20 ms
Interpretation: The pulse repeats every 20 ms; this is not the travel time of the shaft.
Example 2 — Find the duty ratio and 16-bit duty setting for a 1.5 ms pulse in a 20 ms servo frame Given: Frame 20 ms; HIGH pulse 1.5 ms.
d = TON ÷ T d = 1.5 ms ÷ 20 ms d = 0.075 u ≈ round(d × 65,535) u ≈ round(4,915.125) u = 4,915
Interpretation: round means nearest integer. The pulse is approximately 7.5% duty. Its mechanical position depends on the calibrated servo pulse range.
2.12.3 EDU PICO connection
The course material assigns GP6 to the servo signal. The onboard potentiometer is connected to GP28 / ADC2 and can provide a user-adjustable position request. Use the EDU PICO servo connector and follow its printed S, +, − positions. For the servo lead used in this lab, the stated color mapping is: − = GND (brown), + = VCC (red), S = signal to GP6 (orange) .
EDU PICO GP6 · signal output (orange) GP28 / ADC2 · potentiometer input GND · common reference (brown)
→ → →
Positional servo S · SIGNAL to GP6 (orange) + · VCC (red) − · GND (brown)
Power rule: do not power the servo motor from a GPIO pin or the RP2040 3.3 V output. Use the board's intended servo-power arrangement or a supply rated for the servo. If using a separate supply, connect its ground to controller ground. Disconnect power before changing wiring. A stalled servo can draw high current and overheat; reduce the pulse range or mechanical load if it buzzes at an endpoint.
2.12.4 CircuitPython servo control
The course example in 20262027/lecture_examples/07_servo.py uses GP6, 50 Hz, and Adafruit's servo.Servo class. The class converts the requested angle into a pulse width between the configured minimum and maximum. The sample uses 1,000–2,000 μs as a starting range; verify the connected servo before using its full travel.
import board
import pwmio
import time
from adafruit_motor import servo
pwm = pwmio.PWMOut(board.GP6, frequency=50)
arm = servo.Servo(pwm, min_pulse=1000, max_pulse=2000)
try:
for angle in (20, 60, 90, 120, 160):
arm.angle = angle
time.sleep(0.75)
finally:
arm.angle = None
pwm.deinit()
Read the CircuitPython servo setup Code element Meaning PWMOut(board.GP6, frequency=50)Creates a 50 Hz PWM frame on the EDU PICO servo signal pin. One frame lasts 20 ms. servo.Servo(pwm, ...)Wraps the PWM output with an angle-based interface for a positional servo. min_pulse=1000Sets the pulse width associated with the low end of the configured angle range, in microseconds. max_pulse=2000Sets the pulse width associated with the high end of the configured angle range, in microseconds. arm.angle = 90Requests the midpoint of the configured actuation range; the shaft's actual physical position is not measured by the RP2040. arm.angle = NoneStops sending servo pulses so the servo is released; holding torque may be removed. pwm.deinit()Releases the PWM hardware resource when the program ends.
2.12.5 Interactive pulse-width and position model
Move the slider or choose a preset. The simulation changes the requested shaft position and the pulse width in a 20 ms frame. It illustrates the command relationship; it cannot predict a particular servo's real mechanical travel or load.
Commanded angle 90° 0° 90° 180°
Estimated pulse width: 1500 μs
Frame frequency: 50 Hz · period: 20 ms
HIGH-time duty ratio: 7.5%
At 90°, the example pulse is 1.50 ms in each 20 ms frame.
Servo horn and pulse waveform simulation An adjustable horn angle and a 50 hertz waveform. The HIGH pulse length changes with the selected angle while the frame remains 20 milliseconds. Servo position model horn angle follows the command One PWM frame · 20 ms 0 ms 20 ms HIGH pulse Figure 2.27. Interactive model for the example 1,000–2,000 μs servo pulse range at 50 Hz. The HIGH pulse grows with the commanded angle; the 20 ms frame stays the same.
2.12.6 Map the onboard potentiometer to servo position
The EDU PICO potentiometer gives the learner a physical input to change the requested angle. The program scales its reading to a 0°–180° command; the Adafruit servo object then performs the angle-to-pulse conversion.
import analogio
import board
import pwmio
import time
from adafruit_motor import servo
pot = analogio.AnalogIn(board.GP28)
pwm = pwmio.PWMOut(board.GP6, frequency=50)
arm = servo.Servo(pwm, min_pulse=1000, max_pulse=2000)
try:
while True:
angle = int(pot.value * 180 / 65535)
arm.angle = angle
time.sleep(0.02)
finally:
arm.angle = None
pwm.deinit()
pot.deinit()
Map the ADC API reading proportionally from its 0–65,535 range into a requested angle from 0° to 180°. A midpoint reading requests approximately 90°. The worked examples below show the calculation; calibration, pulse limits, backlash and load affect the physical angle.
Worked examples — ADC reading to requested angle Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
r CircuitPython ADC reading on the 0–65,535 API scale θ requested or calculated output-shaft angle (degrees) Example 1 — Find the requested servo angle for an ADC API reading of 32,768 mapped from 0–65,535 to 0–180° Given: ADC API reading 32,768; requested angle range 0–180°.
θ = r × 180° ÷ 65,535 θ = 32,768 × 180° ÷ 65,535 θ ≈ 90.001°
Interpretation: The nominal request is approximately 90°; the physical angle depends on calibration.
Example 2 — Find the requested servo angle for an ADC API reading of 16,384 mapped from 0–65,535 to 0–180° Given: ADC API reading 16,384.
θ = r × 180° ÷ 65,535 θ = 16,384 × 180° ÷ 65,535 θ ≈ 45.001°
Interpretation: Use the API range 65,535 here, not the raw 12-bit maximum of 4095.
2.12.7 Check operation and diagnose problems
With power off, confirm the servo plug's signal, positive, and ground orientation at the EDU PICO servo port. Run the finite angle example with the servo horn unloaded. Confirm that each new angle command moves the horn toward a new position. Turn the onboard potentiometer slowly and compare its direction with the requested angle shown in the Thonny Shell or an optional display. If the servo jitters or resets the board, stop and check servo supply capacity, shared ground, connector orientation, and whether other loads share the supply. If the servo buzzes at an endpoint, narrow min_pulse and max_pulse or reduce the commanded angle range; do not hold a stalled servo at a mechanical stop.
CHAPTER 03
System Inputs YOUR LEARNING GOALS
Chapter 3 learning outcomes By the end of this chapter, students should be able to:
Classify input signals as analogue, digital GPIO states, or digitally communicated sensor data, and select an appropriate acquisition method. Configure and read GPIO inputs in CircuitPython, explain pull-up/pull-down operation, and implement a debounced button-controlled action. Calculate ADC resolution and convert between voltage and digital readings while distinguishing the RP2040 hardware resolution from the analogio output scale. Acquire and scale potentiometer readings, explain analogue temperature-sensor conversion, and read the AHT20 through I²C without confusing digital sensor data with RP2040 ADC measurements. Explain matrix-keypad scanning and determine a pressed key from row-and-column states, identifying the external hardware required. Use acquired input values in a CircuitPython program to update an OLED indication or control an output, and select suitable EDU PICO sensing examples for a stated application. Select a subtopic to view its planned coverage.
9 topics Outline ready · Lessons to follow
CHAPTER 3 / SUBTOPIC 3.1
3.1 Introduction to system inputs
Learning notes RP2040 · CircuitPython · EDU PICO
By the end of this section, you should be able to: explain what an input device and input signal do; distinguish a user command from a measurement of the environment; and classify an example as a digital GPIO input, an analogue input, or digital data sent by a communication bus. Course alignment: CLO1 — explain and classify embedded-system input concepts. Practical CLO2 skills will be assessed in integrated lab tasks after Chapter 5.
3.1.1 What is a system input?
Input is information that enters a system so its controller can respond. The information may come from a person, such as a button press, or from the physical world, such as temperature or light.
Input device A component that detects a user action or a physical condition and makes that information available to the controller.
Input signal The electrical or encoded form of the information that travels from the input device to the microcontroller.
Controller The RP2040 reads the signal, interprets it using the program, and decides what the system should do next.
Figure 3.1 — From a real-world event to a system response Input-to-response path in an embedded system A person or physical condition affects an input device. The device produces a signal which the RP2040 reads and interprets before controlling an output. Event Input device Signal RP2040 Response press / temperature button / sensor voltage / data read + interpret display / actuator The input provides information; the program decides how the system responds.
3.1.2 Inputs can represent commands or measurements
User command A person deliberately asks the system to do something.
EDU PICO example: pressing onboard button A or B gives the program a command such as “change mode”.
Environmental measurement A sensor reports a changing physical quantity, even when nobody presses a control.
EDU PICO example: the AHT20 reports temperature and humidity; the potentiometer provides a manually adjustable level.
Figure 3.2 — EDU PICO input hardware in the course kit. The board includes user controls and sensor modules. Use the pin assignment table below to identify how each one reaches the RP2040.
3.1.3 Three ways the controller receives input
“Digital” can describe either a simple pin state or encoded data. These are both digital, but they are read differently.
Input category What arrives? EDU PICO example How the RP2040 receives it Covered in Digital GPIO state One of two logic states, usually represented as 0 or 1. Onboard button A (GP0) or B (GP1). Read a GPIO pin as a digital input. 3.2 Input operations Analogue level A voltage that can vary across a range. Potentiometer connected to ADC input GP28. An ADC converts the voltage into a number the program can use. 3.3 Analogue inputs Digital bus data Bits grouped and exchanged according to a communication protocol. AHT20 temperature/humidity sensor on I²C (SDA GP4, SCL GP5). The controller communicates with the device using a bus protocol; the reading is not just one HIGH/LOW pin. 3.4 Digital inputs
Remember: an analogue sensor can describe a continuously changing quantity. A digital GPIO input answers a simple state question. A digital sensor may send a multi-bit measurement over a protocol such as I²C.
3.1.4 Explore a digital sensor input The detailed button and potentiometer simulations are placed beside their explanations in 1.2.5 Digital input: active-high and active-low and 1.2.5 ADC input: turn a changing voltage into a number . Here, explore how a digital sensor such as the AHT20 presents measurement data to the controller.
WHAT THE CONTROLLER RECEIVES
Digital measurement over I²C 27 °C · 55% RH
Adjust the illustrative readings. The AHT20 sends measurement data using the I²C protocol; this is more information than a single HIGH/LOW pin state.
AHT20 → SDA GP4 + SCL GP5 → I²C sensor reading
3.1.5 I²C: how the RP2040 reads the AHT20
The AHT20 is a digital sensor . It does not present temperature as one changing voltage or as a single HIGH/LOW pin. Instead, the RP2040 communicates with it using I²C (Inter-Integrated Circuit) , a synchronous serial bus. “Synchronous” means the controller supplies a clock so both devices coordinate when data bits are transferred.
SCL · Serial Clock The clock line. The controller generates timing pulses so the target knows when to send or receive each bit.
SDA · Serial Data The data line. Address, command, acknowledgement, and measurement bits travel on this shared line.
Controller and target The RP2040 controller starts the exchange and selects a target by address. The AHT20 target responds at its address.
On the EDU PICO, the shared I²C bus uses SDA = GP4 and SCL = GP5 . The OLED and AHT20 can share these same two signal wires because each has its own address. In the course setup, the AHT20 address is 0x38 and the OLED is commonly 0x3C. Only the addressed device responds during a transaction.
Figure 3.3 — Shared I²C bus between the EDU PICO RP2040, AHT20 and OLED EDU PICO shared I2C bus with AHT20 and OLED RP2040 GP5 connects to SCL and GP4 connects to SDA. Both the AHT20 at address 0x38 and OLED at 0x3C share the bus. Pull-up resistors connect the bus lines to 3.3 volts. RP2040 I²C controller GP5 · SCL GP4 · SDA SCL · clock SDA · data SCL · shared clock SDA · shared data AHT20 Target · 0x38 OLED Target · 0x3C Both targets share SDA and SCL; the address tells each device when to respond. 3V3 pull-ups are part of the bus electrical arrangement; use the board’s documented bus circuitry.
Why pull-ups? I²C devices generally pull a line LOW or release it; pull-up resistors bring the shared line back HIGH. This lets several devices use the same wires without one device forcing a conflicting HIGH while another pulls LOW. The EDU PICO bus hardware provides the required arrangement, so do not add extra pull-ups unless the board documentation or circuit calls for them.
What happens during one AHT20 reading? Use the step controls to follow a simplified transaction. The animation teaches the order and purpose of the bus events; it is not a live electrical waveform.
Figure 3.4 — I²C timing for an AHT20 measurement request and read Conceptual timing, not to scale. W and R mark the direction bit transmitted on SDA after the 7-bit address; they are not extra signal wires. The sample data bits are illustrative because actual sensor readings change.
I2C SCL and SDA pulse graph with write and read direction bits Start, address 0x38 with write direction zero, measurement command, conversion wait, address 0x38 with read direction one, illustrative data, and stop. R/W is a bit on SDA, not a separate wire. SCL clock SDA data R/W bit IDLE START ADDRESS + W MEASUREMENT COMMAND WAIT ADDRESS + R READ DATA STOP W = 0 R = 1 0xAC · 0x33 · 0x00 + ACK after each byte D7 … D0 · ACK · … · final NACK ≥80 ms START STOP SCL SDA
SCL · CLOCK HIGH
SDA · DATA HIGH
BUS IDLE SCL = HIGH · SDA = HIGH Bus is idle; pull-ups hold both lines HIGH.
Previous Next step Start again
Step 1 of 7 · Bus idle
TRANSACTION EXPLANATION
1. Idle: both lines HIGH When no transfer is in progress, the pull-ups hold SDA and SCL HIGH. The controller can begin a new transaction.
Key idea: The bus is shared, but devices do not talk over one another because the address selects the target.
AHT20 measurement sequence in plain language The RP2040 addresses the AHT20 at 0x38 and writes the measurement trigger command: 0xAC, 0x33, 0x00. The controller waits at least 80 ms for the sensor to complete its measurement, then checks that the sensor is ready. The controller reads the status and measurement bytes. The sensor’s driver unpacks the bytes into temperature and relative humidity values. The AHT20 details above follow the manufacturer’s datasheet. In normal CircuitPython lessons, a sensor library usually handles the low-level command bytes and timing for you.
What the code setup means import board
import busio
i2c = busio.I2C(board.GP5, board.GP4) # SCL first, then SDAbusio.I2C(...)Creates an I²C controller object. CircuitPython’s argument order is clock pin first, then data pin.
board.GP5Connects SCL, the clock line, to EDU PICO GP5.
board.GP4Connects SDA, the data line, to EDU PICO GP4. A driver can then use this bus to communicate with the sensor.
When the bus is shared with the OLED, initialize the bus once and let the device drivers use that same I²C bus. CircuitPython also provides bus scanning to help discover responding addresses; a scan confirms that something responds at an address, but does not prove that the device is the expected model.
Link to the complete system: this section explains how temperature information reaches the RP2040. The separate
1.1.6 temperature-monitor case uses the reading in a control rule and shows how that decision can command the OLED and ventilation fan.
Sources and further reading
3.1.6 Check your understanding
Sources and further reading
CHAPTER 3 / SUBTOPIC 3.2
3.2 Input operations
Lesson developed RP2040 · CircuitPython · EDU PICO
Follow a signal from a physical switch to a voltage, a Boolean value, and a decision in the program.
Learning outcomes · CLO1 (C4, PLO2) Relate input wiring and voltage to the value read by a program. Analyse incorrect bias, reversed interpretation, missed presses and repeated transitions. Justify a suitable pull configuration and reading strategy. The definitions and calculations build towards analysis. Formal CLO2 practical assessment will follow Chapter 5 through integrated programming and hardware tasks.
3.2.1 Configure, read and interpret
Input configuration prepares a pin to receive a signal. In digital input mode, the output driver is disabled and the input circuitry senses the external voltage. An optional pull resistor establishes an idle level.
Select: identify the signal pin and its wiring.Configure: set input direction and an appropriate pull.Read: obtain the electrical logic level.Interpret: decide what that level means for this circuit.Repeat: read often enough for the event you want to detect.
Logic level describes the electrical state. Active state describes the event of interest. For an active-low button, a LOW voltage means “pressed”.
3.2.2 Electrical behaviour: voltage is not the same as logic
Input threshold is a voltage limit used to specify reliable logic recognition. For RP2040 GPIO at IOVDD = 3.3 V , the datasheet specifies VIL(max) = 0.8 V and VIH(min) = 2.0 V . Within the intended 0–3.3 V signal range, voltages between these limits have no guaranteed logic interpretation. These limits are not exact switching trip points.
Illustrative GPIO voltage: 3.30 V
RP2040 input voltage regions for 3.3 volt I/O supply LOW Not guaranteed HIGH 0 V 0.8 V 2.0 V 3.3 V
HIGH → True
Figure 3.5. Move the voltage through the guaranteed LOW, unspecified and guaranteed HIGH regions. This illustrates specification limits; it does not simulate a particular pin’s switching threshold.
High input impedance means that sensing the voltage draws very little current. The GPIO leakage specification is up to 1 µA under the datasheet conditions. This is distinct from current flowing through a pull resistor and closed switch. Floating input means no circuit establishes a reliable voltage; coupled noise or stored charge can change its reading.
Connection rules: use a common ground reference and 0–3.3 V GPIO signals on this platform. Do not connect 5 V directly to an RP2040 GPIO. GP0 means GPIO0, not physical header pin 0. Use the course board pin mapping when connecting hardware.
Technical values: RP2040 datasheet, §5.5.3.4, I/O electrical characteristics .
3.2.3 Pull resistors and a worked current calculation
Pull-up biases an otherwise undriven input towards 3.3 V. Pull-down biases it towards ground. A switch connected to the opposite rail overrides the weak bias when closed.
Arrangement Switch open Switch closed Interpretation Pull-up; switch to GND HIGH / True LOW / False Active-low; EDU PICO button A/B arrangement Pull-down; switch to 3.3 V LOW / False HIGH / True Active-high; external teaching circuit No bias and no external drive Floating Depends on switch rail Unreliable while open
Use the existing 1.2.5 active-high/active-low circuit simulation to compare the two physical circuits. RP2040’s internal pull-up and pull-down resistances are specified as 50–80 kΩ ; they are weak and are not precision resistors. An external resistor allows a chosen nominal resistance. Lower resistance gives stronger bias but draws more current when the switch closes; higher resistance makes leakage, interference and wiring capacitance more significant.
Worked example — external 10 kΩ pull-up, switch closed to GND Assume ideal 3.3 V supply and negligible switch resistance.
Current follows 3.3 V → resistor → switch → GND . It is not 0.33 mA flowing into the input circuitry. With a 50–80 kΩ internal pull, the same ideal closed-switch calculation gives approximately 41–66 µA.
Compare an external pull-up value: 4.7 kΩ 10 kΩ 47 kΩ
A 10 kΩ value is a teaching example, not a universal choice for every cable, sensor or bus.
Worked examples — pull-resistor current and power Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
V voltage (V) R resistance (Ω) I current (A) P power (W) Example 1 — Find current and power in a 10 kΩ pull-up resistor with 3.3 V across it Given: Voltage across resistor 3.3 V; resistance 10,000 Ω.
I = V ÷ R I = 3.3 V ÷ 10,000 Ω I = 0.00033 A I = 0.33 mA P = V2 ÷ R P = (3.3 V)2 ÷ 10,000 Ω P = 0.001089 W P = 1.089 mW
Interpretation: This is the resistor dissipation with the switch closed.
Example 2 — Find current and power in a 4.7 kΩ pull-up resistor with 3.3 V across it Given: Same voltage; resistance 4700 Ω.
I = V ÷ R I = 3.3 V ÷ 4700 Ω I ≈ 0.702 mA P = V2 ÷ R P = (3.3 V)2 ÷ 4700 Ω P ≈ 2.317 mW
Interpretation: Lower resistance increases both current and resistor dissipation.
3.2.4 CircuitPython: prepare and read button A
Boolean is a value with two possibilities: True or False. Reading button.value returns the pin’s digital state; it does not automatically mean “button pressed”.
import time
import board
import digitalio
# EDU PICO button A: GP0, active-low.
with digitalio.DigitalInOut(board.GP0) as button:
button.direction = digitalio.Direction.INPUT
button.pull = digitalio.Pull.UP
while True:
raw = button.value
pressed = not raw
print("raw:", raw, "pressed:", pressed)
time.sleep(0.05)
Code element Purpose and meaning digitalio.DigitalInOut(board.GP0)Creates a digital pin object; board.GP0 identifies the pin. button.direction = digitalio.Direction.INPUTConfigures reading. Set the pull after setting direction. button.pull = digitalio.Pull.UPEnables the internal pull-up. Pull.DOWN selects pull-down; None disables the internal pull, not any external resistor. raw = button.valueSamples the pin: HIGH → True; LOW → False. pressed = not rawInverts the raw state because the onboard button is active-low. time.sleep(0.05)Waits 50 ms. Actual time between reads also includes execution and printing. with ... as button:Names the object and releases its pin when the block exits, including when an exception unwinds it.
The shorter configuration button.switch_to_input(pull=digitalio.Pull.UP) can replace the two direction/pull assignments. In this method, pull is the parameter and digitalio.Pull.UP is the supplied argument. The loop prints repeatedly while held: reading a state is different from counting a new press.
API reference: CircuitPython digitalio . Course pin mapping: 20262027/circuitpython_basics.html, push-button example.
3.2.5 Interactive GPIO: wiring → voltage → code
First use switch to GND + pull-up for the onboard button A model. Then compare an external switch-to-3.3 V circuit or deliberately choose the wrong pull. These are virtual wiring choices; changing a software pull does not physically rewire the onboard button.
Switch connects GPIO to GND · active-low 3.3 V · active-high Input bias Pull.UP Pull.DOWN None · no external bias Press button Reset to button A
Configurable switch and pull resistor connected to an RP2040 digital input RP2040 GP0 · INPUT 3.3 V (pull-up) Bias disconnected GND 3.3 V · HIGH Conceptual circuit · ideal switch · no contact bounce
raw = button.value if pressed: print("Pressed") else: print("Released") Simulated console
Figure 3.6. A defined voltage produces a raw Boolean; the program interprets it using the circuit’s active polarity. With a floating pin, this teaching model displays “undetermined”; actual digital reads still return True or False but cannot be relied on.
3.2.6 Polling: a short event can occur between reads
Polling means repeatedly checking an input in software. Polling interval is the time between successive checks. For ideal regular sampling, fpoll = 1/Tpoll : 50 ms corresponds to 20 checks/s; 10 ms corresponds to 100 checks/s.
A held, stable change can wait almost one polling interval before detection. A shorter pulse can fit entirely between samples. Printing, other work and sleep contribute to the real loop interval, so a sleep duration alone does not guarantee a sampling rate.
Ideal polling interval 5 ms 10 ms 25 ms 50 ms 20 ms press begins at 20 ms
Move the press between sample dots. Filled green dots detect LOW; outlined dots see HIGH. The ideal model includes the press-start instant and excludes its release instant; physical sampling exactly on an edge is not guaranteed.
Figure 3.7. Fixed 100 ms window: compare pulse position and polling interval. Several LOW samples during one held press are several readings of the same event.
Worked examples — polling interval Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Ts sampling interval (s) fs sampling frequency (samples/s) Example 1 — Find the polling frequency given a 50 ms sampling interval Given: Regular polling interval 0.050 s.
fs = 1 ÷ Ts fs = 1 ÷ 0.050 s fs = 20 samples/s
Interpretation: A short press entirely between samples may be missed.
Example 2 — Find the polling frequency given a 10 ms sampling interval Given: Regular polling interval 0.010 s.
fs = 1 ÷ Ts fs = 1 ÷ 0.010 s fs = 100 samples/s
Interpretation: Faster sampling reduces the gap but does not itself debounce a switch.
3.2.7 Switch bounce and stable-time debouncing
Contact bounce is a burst of transitions as a mechanical contact settles. Debouncing qualifies those transitions before the program accepts a new state. A pull resistor establishes the open-switch voltage; it does not remove the mechanical bounce.
Stable-time debounce accepts a new level only after it has remained unchanged for a chosen time. A longer interval rejects more brief disturbances but delays response and can suppress a legitimate short press. Choose it for the switch and application; 10 or 20 ms is an example, not a universal specification.
Required stable time: 10 ms
Compare 0 ms with 10 ms. This example samples at an ideal 1 ms interval. One physical press-and-release includes chatter on both edges; every accepted HIGH→LOW transition would count as a press.
Figure 3.8. Illustrative bounce over a fixed 140 ms window. Raw contact activity stays the same while the debounce setting changes the accepted waveform and press count.
Annotated example: print once per debounced press candidate tracks the most recently observed level. candidate_since records when it last changed. stable is the accepted state. A candidate must persist for DEBOUNCE_S before acceptance. This example initializes from the current reading, so a button held during startup is not counted as a new press.
import time
import board
import digitalio
DEBOUNCE_S = 0.020 # Example: 20 ms of stable readings
with digitalio.DigitalInOut(board.GP0) as button:
button.switch_to_input(pull=digitalio.Pull.UP)
stable = button.value
candidate = stable
candidate_since = time.monotonic()
while True:
raw = button.value
now = time.monotonic()
if raw != candidate:
candidate = raw
candidate_since = now
if candidate != stable and now - candidate_since >= DEBOUNCE_S:
stable = candidate
if not stable: # Accepted falling edge: active-low press
print("New press")
time.sleep(0.001) # Actual interval includes execution timetime.monotonic() supplies an increasing time reference for elapsed-time comparisons. Continuous polling must still be fast enough to observe the relevant changes.
Further reading: Adafruit’s contact-bounce explanation and CircuitPython time reference .
3.2.8 Guided analysis and tutorial
Example 1 — a released button is reported as “Pressed” A switch connects GP0 to GND. The program uses a pull-down and interprets LOW as pressed. The open switch reads LOW from the pull-down; closing it also connects it to LOW. Both positions look pressed. Use the pull-up appropriate to the wiring, then apply pressed = not raw.
Example 2 — predict a sample at 1.4 V At 3.3 V I/O supply, 1.4 V is above the guaranteed LOW region and below the guaranteed HIGH region. A True or False reading may occur, but neither is guaranteed by these limits. Restore a valid voltage; do not fix this by merely inverting the Boolean.
Tutorial — calculate current and analyse missed presses For a 4.7 kΩ external pull-up and a closed switch to GND at 3.3 V, calculate resistor current and power. If polling occurs at 0, 50 and 100 ms, predict whether a press from 20 to 40 ms is detected. Would adding a 20 ms debounce requirement alone solve the missed-press problem? Worked answers: I = 3.3/4700 ≈ 0.702 mA; P = 3.3²/4700 ≈ 2.317 mW. No sample lands inside the press, so it is missed. Debouncing cannot reconstruct an event never sampled; a suitable polling strategy is needed first.
3.2.9 Check your understanding
Next: 3.3 develops analogue input measurement and ADC conversion. Detailed button applications return in 3.4.1.
CHAPTER 3 / SUBTOPIC 3.3
3.3 Analogue inputs Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Identify the analogue signal, suitable interface, reference and physical unit; explain how sampling affects what the program observes.
Explanations and calculations build towards analysing a measurement path. Formal CLO2 hardware/programming assessment follows Chapter 5.
An analogue input tells the program how much a quantity has changed. The measurement chain must preserve the meaning of the voltage from the circuit to the displayed value.
Definitions: signal, measurement and unit
Analogue signal A signal whose amplitude can vary continuously over a range. A potentiometer wiper is a familiar voltage example.
Sample One observation at a particular instant. The program receives a sequence of samples, even when the physical voltage changes smoothly.
Reference voltage The voltage scale against which the ADC expresses an input. Knowing a code alone is insufficient to recover voltage.
Measurement chain means the sequence connecting the physical quantity to a useful result: quantity → sensor or control → voltage → ADC code → voltage estimate → unit or percentage . Temperature, pressure and position require different conversion relationships.
Example Signal delivered to RP2040 Suitable interface Program result EDU PICO potentiometer Variable wiper voltage on GP28 ADC via analogio Voltage or knob percentage External analogue sensor, after checking board compatibility Voltage representing a measured quantity Available ADC input and any required conditioning A unit calculated from the sensor relationship EDU PICO AHT20 Encoded temperature/humidity data on I²C GP4 SDA / GP5 SCL with a sensor driver Degrees Celsius and relative humidity
Continuous quantity does not imply an analogue electrical interface. Ambient temperature varies continuously, but the onboard AHT20 communicates digitally. Section 3.3.2 compares the two measurement paths; it does not connect the AHT20 to an RP2040 ADC pin.
Observe a changing voltage
Sampling rate is the number of measurements per second: fs = 1/Ts . Change the interval below and compare the sample dots with the continuous input. A signal can change substantially between samples.
Signal frequency 1 Hz 4 Hz Ideal sampling interval 50 ms · 20 samples/s 100 ms · 10 samples/s 250 ms · 4 samples/s
Figure 3.9. Green curve: illustrative continuous voltage. Blue dots and dashed connecting lines: ideal samples; the dashed line is a visual guide, not a reconstructed measurement. Try 4 Hz with a 250 ms interval: repeating the same sampling phase hides the change.
Aliasing occurs when sampling makes different signal behaviour appear indistinguishable. For a band-limited signal, sampling above twice its highest frequency is a theoretical minimum; practical design also needs bandwidth control and margin. This introductory graph illustrates the problem rather than modelling a complete acquisition system.
Prepare a trustworthy input
Range and ground: use the documented 0–3.3 V teaching range and a common reference ground. Never treat a sensor’s 5 V supply rating as proof its output is safe for the ADC.Signal conditioning: a divider, buffer or filter may be required to match an external signal to the input. Confirm the complete circuit before connecting it.Source and reference quality: interference, reference error and loading can affect readings. Extra displayed decimal places do not prove extra accuracy.Board allocation: an ADC-capable chip pin may already serve another onboard circuit. In these lessons the onboard potentiometer uses GP28; do not repurpose shared pins without checking the EDU PICO wiring.
Follow the three detailed lessons
Quantization, 12-bit conversion, API scaling, calculations and annotated code.
Sensor sensitivity, analogue versus I²C readings, and the EDU PICO AHT20/OLED example.
Divider operation, GP28 readings, direction, calibration and percentage mapping.
For the earlier picture-based knob demonstration, revisit 1.2.5 ADC input .
Guided analysis A temperature value changes continuously. Must the sensor use an ADC pin? No. Identify the electrical interface. A voltage-output sensor needs voltage acquisition; the EDU PICO AHT20 delivers digital data through I²C. The physical quantity and the communication format are separate choices.
Hardware and API references: RP2040 datasheet, §4.9 ; CircuitPython analogio . EDU PICO assignments follow the local course file 20262027/circuitpython_basics.html.
CHAPTER 3 / SUBTOPIC 3.3.1
3.3.1 Analogue-to-digital converter — ADC Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Distinguish hardware resolution from API representation, calculate ideal codes and voltages, and analyse reference or sampling errors.
Explanations and calculations build towards analysing a measurement path. Formal CLO2 hardware/programming assessment follows Chapter 5.
3.3.1.1 What the ADC does ADC means analogue-to-digital converter. It samples a voltage and assigns a numerical code. Quantization groups a continuous range into discrete intervals. Resolution specifies the number of available codes; it is different from measurement accuracy.
The RP2040 has a 12-bit ADC: 2¹² = 4096 codes, numbered 0–4095 . Its multiplexer selects one input at a time. The chip offers four external channels on GP26–GP29 plus an internal temperature-sensor channel. Board availability differs: use the documented EDU PICO GP28 potentiometer connection here.
The ADC hardware can reach 500 ksample/s with a 48 MHz ADC clock and 96 clock cycles per conversion. This is a hardware capability, not the rate of a Python loop with printing or delays. Nominal 12-bit resolution also does not guarantee 12 bits of useful accuracy: the datasheet characterises effective resolution separately.
From a real voltage to an ADC number—and back to a voltage estimate 1 · Analogue input The input can be any voltage from 0 V to 3.3 V.
Example input: 1.6500 V
→
2 · ADC quantization The ADC places the measured voltage into one voltage bin.
The highlighted bin is assigned code 2048 .
→
3 · Digital output Raw ADC output: code 2048
Reconstructed voltage estimate: 1.6504 V
ADC means analogue-to-digital converter: it turns a measured voltage into a digital code.
Quantization means grouping nearby voltages into bins; all voltages inside one bin produce the same code.
Resolution is the number of available codes. The RP2040 has 12 bits and therefore 4096 codes (0–4095). Across 3.3 V, each ideal bin is about 0.8057 mV wide. This code-based voltage estimate is close to the input but cannot recover its exact value.
Example shown: a 1.6500 V input falls in bin 2048. The ADC output is a number; the voltage shown at the output is an estimate reconstructed from that number.
3.3.1.2 Quantization and voltage equations Voltage-bin width and LSB step: in an ideal ADC with equally spaced codes, these names refer to the same voltage increment. These notes use ΔV for that ideal voltage-bin width.
N ADC resolution in bits L number of distinct ADC codes, or voltage bins VREF ADC reference voltage (V) ΔV ideal voltage-bin width (V); also called the LSB step L = 2N ΔV = VREF ÷ L ΔV = VREF ÷ 2N LSB step = ΔV
This lesson’s ideal model uses equal bins starting at zero and clips the full-scale endpoint to the highest code. floor means round down. Real ADC transition locations, noise and errors need not match this ideal model exactly.
Worked example: for N = 12 and VREF = 3.3 V, ΔV = 3.3/4096 ≈ 0.8057 mV . At VIN = 1.65 V, k = floor(2048) = 2048 . At 3.3 V, use 4095 , because code 4096 does not exist.
Worked examples — ideal ADC quantization Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
N number of bits L number of distinct code levels or addressed locations Vref reference voltage (V) Vin input voltage (V) ΔV ideal ADC voltage-bin width (V) k raw ADC code (0–4095 for the 12-bit example) Example 1 — Find the number of codes and voltage-bin width for a 12-bit ADC with a 3.3 V reference Given: 12-bit ADC; reference 3.3 V.
L = 2N L = 212 L = 4096 ΔV = Vref ÷ L ΔV = 3.3 V ÷ 4096 ΔV ≈ 0.000805664 V ΔV ≈ 0.805664 mV
Interpretation: There are 4096 bins, with code labels 0 through 4095.
Example 2 — Find the ideal 12-bit ADC code for a 0.825 V input and 3.3 V reference using the bin model Given: Input 0.825 V; reference 3.3 V; ideal bin model.
k = min(L − 1, floor[Vin ÷ Vref × L]) k = min(4095, floor[0.825 V ÷ 3.3 V × 4096]) k = 1024
Interpretation: floor rounds down; min selects the smaller value to cap the code at 4095. This bin model differs from the approximate endpoint interpolation used in 1.2.11.
3.3.1.3 Interactive conversion and staircase
Input voltage 1.6500 V 3.3 V reference · move the slider ViewRP2040 ADC · 12 bits · 4096 bins Coarse teaching model · 3 bits · 8 bins
Read the diagram: the top bar shows the full 0–3.3 V range. The lower graph magnifies nearby bins; the gold bin is the voltage interval represented by the selected code. The min/max labels mark that interval's edges. The estimated output voltage is a representative value reconstructed from the code, so it need not equal either edge. Change the input to see when the code steps up.
Raw ADC code
Voltage-bin width, ΔV
CircuitPython API value
Estimated API output voltage
Figure 3.10. Top: the complete 0–3.3 V range, with the selected neighbourhood outlined. Bottom: an enlarged view of equal-width ADC bins; the gold bin shows the voltage interval that produces the selected raw code. Labeled x-axis ticks show input voltage. Colored leader lines point from the highlighted bin's lower and upper x-axis boundaries to their minimum and maximum voltage values. The ADC output is a digital code; the estimated output voltage is a representative value reconstructed from that code, not the bin minimum or maximum and not the exact input voltage. For the RP2040, each ideal bin is ΔV = 3.3 V ÷ 4096 ≈ 0.8057 mV. The 3-bit view uses eight wide bins only as a teaching comparison; it does not change the RP2040’s 12-bit ADC.
3.3.1.4 Why CircuitPython returns a 16-bit number
AnalogIn.value uses the API range 0–65535 across platforms. Expanding a 12-bit reading into that range does not add measurements or improve accuracy. The simulator uses the current RP2040 port’s bit-expansion mapping; not every integer in the API range is an independently measurable level.
Quantity Range / equation Interpretation Raw hardware code k 0–4095 One of 4096 ADC code values API reading r 0–65535 Software representation of the conversion Estimated voltage V ≈ r × reference_voltage / 65535 Normalised endpoint estimate using the API value
The 4096 denominator defines ideal hardware bin width; 65535 is the largest API value used by the voltage-estimation formula. These formulas serve different purposes.
Technical detail: the RP2040 port’s scaling The inspected implementation expands raw k using (k << 4) | (k >> 8). Thus k = 2048 maps to r = 32776 and V ≈ 1.6504 V with a 3.3 V nominal reference. The small difference from 1.6500 V reflects the ideal bin/API mapping, not additional analogue resolution. This implementation detail may vary by port or firmware.
Worked examples — API voltage estimate Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
r CircuitPython ADC reading on the 0–65,535 API scale Vin input voltage (V) Vref reference voltage (V) Example 1 — Estimate input voltage from an ADC API reading of 32,776 on a 0–65,535 scale with a 3.3 V reference Given: API reading 32,776; reference 3.3 V.
Vin ≈ (r ÷ 65,535) × Vref Vin ≈ (32,776 ÷ 65,535) × 3.3 V Vin ≈ 1.65043 V
Interpretation: The API number does not add physical ADC resolution.
Example 2 — Estimate input voltage from an ADC API reading of 49,151 on a 0–65,535 scale with a 3.3 V reference Given: API reading 49,151; reference 3.3 V.
Vin ≈ (r ÷ 65,535) × Vref Vin ≈ (49,151 ÷ 65,535) × 3.3 V Vin ≈ 2.47499 V
Interpretation: Use the measured reference when accuracy matters; 3.3 V is the course assumption.
3.3.1.5 Read one sample and reuse it
import time
import board
import analogio
with analogio.AnalogIn(board.GP28) as pot:
while True:
reading = pot.value # One acquisition
voltage = reading * pot.reference_voltage / 65535
print("ADC: {} Voltage: {:.3f} V".format(reading, voltage))
time.sleep(0.1)
Code element Purpose analogio.AnalogIn(board.GP28)Creates an analogue input on the course potentiometer pin. pot.valueAcquires a reading. Cache it so all displayed calculations refer to the same sample. pot.reference_voltageReports the port’s configured reference value. The RP2040 implementation returns nominal 3.3 V; it does not measure the actual supply. {:.3f}Formats three decimal places. Formatting does not improve accuracy. withReleases the input when the block exits.
3.3.1.6 Calculation tutorial and error analysis
Calculate the ideal code at 0.825 V k = floor(0.825/3.3 × 4096) = 1024 . It is one quarter of the reference voltage. The highest code remains 4095.
A reference mismatch: actual 3.2 V, assumed 3.3 V For a true input of 1.6 V, the converter is at half of its actual reference. Using 3.3 V to interpret that result gives approximately 1.65 V , about 0.05 V high. Averaging more samples cannot correct a wrong voltage scale; measure or calibrate the reference relationship.
Noise causes reading variation. Averaging can reduce some random variation but adds delay and does not repair systematic error, poor grounding or an unsuitable input range.
Sources: RP2040 datasheet §4.9 ; analogio API ; RP2040 CircuitPython AnalogIn implementation .
CHAPTER 3 / SUBTOPIC 3.3.2
3.3.2 Temperature sensor Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Compare voltage-output and digital temperature sensors, interpret sensitivity/offset, and trace the AHT20 reading to text drawn on the OLED.
Explanations and calculations build towards analysing a measurement path. Formal CLO2 hardware/programming assessment follows Chapter 5.
3.3.2.1 Temperature, sensitivity and offset
Temperature sensor converts a thermal condition into an electrical measurement. Its interface may supply a voltage or digital data. Sensitivity is the output change per unit of temperature. Offset is an output baseline in a stated model.
For this hypothetical analogue sensor, the output at 0 °C is 0.50 V and the sensitivity is 0.010 V/°C. Subtract the offset from the measured voltage, then divide by sensitivity. The worked examples below show each step. This model is not the AHT20 specification.
Subtracting the offset matters: simply dividing 0.75 V by 0.010 V/°C gives an incorrect 75 °C.
Worked examples — hypothetical analogue temperature sensor Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
V voltage (V) V0 sensor offset at 0 °C (V) S sensor sensitivity (V/°C) TC temperature (°C) Example 1 — Find temperature from 0.75 V given a 0.50 V offset and 0.010 V/°C sensitivity Given: Offset 0.50 V; sensitivity 0.010 V/°C; output 0.75 V.
TC = (V − V0 ) ÷ S TC = (0.75 V − 0.50 V) ÷ (0.010 V/°C) TC = 25 °C
Interpretation: This illustrative linear sensor is not the digital AHT20.
Example 2 — Find temperature from 0.92 V given a 0.50 V offset and 0.010 V/°C sensitivity Given: Same hypothetical sensor; output 0.92 V.
TC = (V − V0 ) ÷ S TC = (0.92 V − 0.50 V) ÷ (0.010 V/°C) TC = 42 °C
Interpretation: Subtract the offset before dividing by sensitivity.
3.3.2.2 Compare the two measurement paths
Illustrative temperature 25.0 °C Hypothetical analogue sensor Temperature → voltage → RP2040 ADC → unit conversion
EDU PICO AHT20 Temperature → internal sensor electronics → I²C data → driver property
ILLUSTRATIVE OLED
Figure 3.11. One temperature represented by two different interfaces. The analogue side includes ideal quantization; the digital side illustrates a driver/display value. Sensor noise, accuracy, thermal lag and real I²C timing are not modelled.
The onboard AHT20 uses I²C, not GP28. Its internal conversion is handled inside the sensor; the RP2040 receives encoded data. The RP2040’s internal die-temperature channel is also distinct from the AHT20 ambient sensor. Review
3.1.5 and its I²C walkthrough for bus timing.
3.3.2.3 EDU PICO connections and library parameters
Connection / object Purpose 3.3 V and GND Onboard supply and common reference. SDA · GP4 Shared I²C data. SCL · GP5 Shared I²C clock. AHT20 address 0x38 Selects the sensor on the shared bus. adafruit_ahtx0.AHTx0(i2c, address=0x38)i2c is the existing bus object; address identifies the target. The default is 0x38.sensor.temperatureTemperature in °C through the driver. sensor.relative_humidityRelative humidity in %. Humidity is a separate measured quantity.
Install the matching CircuitPython bundle libraries: adafruit_ahtx0, adafruit_bus_device, and the SSD1306 driver dependencies used in 2.7 OLED interfacing . Use one I²C bus object for both sensor and display.
3.3.2.4 Complete example: temperature and humidity on OLED
import time
import board
import busio
import adafruit_ssd1306
import adafruit_ahtx0
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
sensor = adafruit_ahtx0.AHTx0(i2c, address=0x38)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
while True:
temperature = sensor.temperature
humidity = sensor.relative_humidity
oled.fill(0)
oled.text("Temp: {:.1f} C\nRH: {:.1f}%".format(
temperature, humidity), 0, 16, 1, size=1)
oled.show()
print(temperature, humidity)
time.sleep(1)
oled.text() draws the formatted values into the OLED buffer; oled.show() sends the buffer to the display. The first {:.1f} receives temperature, the second receives humidity, and \n starts a second line. The temperature and humidity properties may acquire separate measurements, so the program does not promise an atomic snapshot.
3.3.2.5 Technical interpretation and tutorial
Thermal response time describes how quickly the sensor follows a temperature change. Faster display refresh cannot remove physical thermal lag. Placement near warm components, airflow and reference-instrument quality affect interpretation; a displayed decimal place is not a guarantee of sensor accuracy.
Calculate 0.92 V using the hypothetical analogue model T = (0.92 − 0.50)/0.010 = 42 °C . First identify the sensor’s relationship; this equation must not be applied to the AHT20’s I²C bytes or to an arbitrary ADC code directly.
The temperature changes but the GPIO reads only True. Diagnose the interface choice. A digital GPIO read only tests a logic level. An analogue voltage needs ADC conversion; the AHT20 needs its I²C driver. Choose the interface according to the device output, then convert or format its reading.
The complete ventilation-control rule remains in 1.1.6 ; here the aim is obtaining and interpreting the measurement.
Source: Adafruit AHTx0 driver API . Wiring and display setup follow the existing EDU PICO course examples. The linear analogue-sensor model is an explicitly assumed teaching example.
CHAPTER 3 / SUBTOPIC 3.3.3
3.3.3 Potentiometer Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Analyse a voltage divider, calculate wiper voltage, interpret GP28 readings and distinguish physical position from calibrated percentage.
Explanations and calculations build towards analysing a measurement path. Formal CLO2 hardware/programming assessment follows Chapter 5.
3.3.3.1 The potentiometer as a voltage divider
Potentiometer is a resistive element with two end terminals and a movable contact called the wiper . Moving the wiper divides the element into two resistances. With the end terminals at 3.3 V and GND, it provides a variable voltage to the ADC.
Rhigh is between 3.3 V and the wiper; Rlow is between the wiper and GND. The formula assumes negligible ADC loading. For an ideal linear 10 kΩ element at its midpoint, both parts are 5 kΩ and Vwiper = 1.65 V. Real potentiometers have resistance/taper tolerances and may not reach ideal endpoints.
Worked examples — potentiometer divider Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Vsupply supply voltage (V) Rlow resistance from wiper to ground (Ω) Rhigh resistance from supply to wiper (Ω) Vwiper potentiometer wiper voltage (V) I current (A) Example 1 — Find the wiper voltage given a 3.3 V supply and two 5 kΩ potentiometer sections Given: Supply 3.3 V; upper and lower resistances both 5 kΩ.
Vwiper = Vsupply × Rlow ÷ (Rhigh + Rlow ) Vwiper = 3.3 V × 5 kΩ ÷ (5 kΩ + 5 kΩ) Vwiper = 1.65 V
Interpretation: Assume negligible loading at the wiper.
Example 2 — Find wiper voltage and track current given 3.3 V, 7.5 kΩ above the wiper and 2.5 kΩ below it Given: Upper resistance 7.5 kΩ; lower resistance 2.5 kΩ; supply 3.3 V.
Vwiper = 3.3 V × 2.5 kΩ ÷ (7.5 kΩ + 2.5 kΩ) Vwiper = 0.825 V I = Vsupply ÷ (Rhigh + Rlow ) I = 3.3 V ÷ 10,000 Ω I = 0.33 mA
Interpretation: The unloaded track current is unchanged when the wiper moves.
3.3.3.2 EDU PICO GP28 and an interactive divider
The course potentiometer connects to GP28 / ADC2 . The earlier 1.2.5 picture illustrates a generic external GP26/ADC0 circuit; use GP28 for this onboard example.
Knob position 50% Reverse outer terminals (virtual comparison)Reset
Linear potentiometer knob and divided resistance connected to GP28 Virtual knob 3.3 V GND Rhigh = 5 kΩ Rlow = 5 kΩ Wiper → GP28 1.650 V Ideal raw ADC
API reading
Estimated percentage
Figure 3.12. An ideal linear 10 kΩ divider, 3.3 V reference and 12-bit bin model. Reversing the virtual outer connections reverses the voltage direction; it does not rewire the EDU PICO board. The pointer rotates about the centre of the knob.
3.3.3.3 Read voltage and map to percentage
import time
import board
import analogio
with analogio.AnalogIn(board.GP28) as pot:
while True:
reading = pot.value
voltage = reading * pot.reference_voltage / 65535
percent = reading * 100 / 65535
print("{} | {:.3f} V | {:.1f}%".format(
reading, voltage, percent))
time.sleep(0.1)
reading stores one acquired value. The two calculations share that sample. 100/65535 maps the API range to a percentage; it is a software scale, not a new ADC setting. That percentage can become an output request, such as display level or a PWM duty-cycle target. It does not supply power to a load.
Worked examples — ADC voltage and percentage Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
r CircuitPython ADC reading on the 0–65,535 API scale Vref reference voltage (V) Vin input voltage (V) p percentage on a 0–100 scale (%) Example 1 — Find input voltage and percentage for ADC API reading 16,384 on a 0–65,535 scale with a 3.3 V reference Given: Reading 16,384; nominal reference 3.3 V.
Vin ≈ (r ÷ 65,535) × Vref Vin ≈ (16,384 ÷ 65,535) × 3.3 V Vin ≈ 0.82501 V p = 100 × r ÷ 65,535 p = 100 × 16,384 ÷ 65,535 p ≈ 25.0004%
Interpretation: Voltage and percentage use the same fraction of the API range.
Example 2 — Find input voltage and percentage for ADC API reading 49,151 on a 0–65,535 scale with a 3.3 V reference Given: Reading 49,151; nominal reference 3.3 V.
Vin ≈ (49,151 ÷ 65,535) × 3.3 V Vin ≈ 2.47499 V p = 100 × 49,151 ÷ 65,535 p ≈ 74.9996%
Interpretation: Small differences from exact quarter points are normal for integer readings.
3.3.3.4 Calibration and smoothing
Endpoint calibration maps the measured minimum and maximum positions to a chosen software range. If measured values are low and high, use the following after ensuring high > low.
Worked calibration: low = 1000, high = 64000, reading = 32500 With measured endpoints 1000 and 64,000, a reading of 32,500 represents 50%. The worked examples below show the calibrated mapping. Calibration changes the scale but does not remove all noise or non-linearity.
Averaging combines several samples to reduce some random variation. It also spreads the observation over time and delays response. Keep raw and averaged values conceptually separate, and do not claim that averaging repairs a wrong reference or disconnected wiper.
Worked examples — calibrated percentage Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
r CircuitPython ADC reading on the 0–65,535 API scale rlow measured ADC reading at the low calibration endpoint rhigh measured ADC reading at the high calibration endpoint p percentage on a 0–100 scale (%) Example 1 — Find the calibrated percentage for reading 32,500 given endpoints 1000 and 64,000 Given: Low reading 1000; high reading 64,000; current reading 32,500.
p = 100 × (r − rlow ) ÷ (rhigh − rlow ) p = 100 × (32,500 − 1000) ÷ (64,000 − 1000) p = 50%
Interpretation: Use distinct calibration endpoints; a zero denominator is invalid.
Example 2 — Find the calibrated percentage for reading 16,750 given endpoints 1000 and 64,000 Given: Same endpoints; current reading 16,750.
p = 100 × (16,750 − 1000) ÷ (64,000 − 1000) p = 25%
Interpretation: Clamp out-of-range results to 0–100% after calculating.
3.3.3.5 Calculation and diagnosis tutorial
Rhigh = 7.5 kΩ and Rlow = 2.5 kΩ: find voltage, ideal ADC code and track current V = 3.3 × 2.5/(7.5 + 2.5) = 0.825 V . Ideal k = floor(0.825/3.3 × 4096) = 1024 . Track current = 3.3/10000 = 0.33 mA , approximately constant as the unloaded wiper moves.
The reading jumps randomly when the wiper lead is disconnected The ADC input is floating. Check the wiper connection and common ground before changing code or adding averaging. Enabling a digital pull resistor changes the divider/loading and is not the normal way to read this analogue control.
References: analogio API and the local EDU PICO GP28 examples in 20262027/circuitpython_basics.html. Divider calculations and the diagrams are original teaching models.
CHAPTER 3 / SYSTEM INPUTS
3.4 Digital inputs Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Analyse how interface, timing and interpretation turn digital signals into useful application information.
Formal programming and hardware assessment under CLO2 follows Chapter 5.
A digital input can report a switch state, a key event or an encoded sensor measurement. Identify the interface before deciding how to read and interpret it.
Definitions: level, state and data Digital level A voltage interpreted as logic LOW (0) or HIGH (1). The receiver uses voltage thresholds; the physical wire still carries a voltage.
Logical state The meaning assigned by the program, such as “pressed” or “released”. Active-low wiring means LOW represents an active input.
Digital data A sequence of bits encoding information. A multi-bit humidity reading is not obtained by treating SDA as one Boolean value.
Input example Electrical interface Program information Interpretation Buttons A / B GP0 / GP1 GPIO True or False Apply active-low meaning, then detect state or event. AHT20 humidity I²C: SDA GP4, SCL GP5 Relative humidity (%) A numerical quantity transported digitally; see 3.1.5 I²C walkthrough . APDS9960 light / colour Shared I²C bus Red, green, blue and clear channel counts Clear is a broad light channel; raw counts are not automatically lux. APDS9960 proximity / gesture Shared I²C bus Proximity count or direction event Proximity is not a direct centimetre measurement. A gesture is an interpreted motion event. Digital microphone PDM clock GP3 / data GP2 Audio samples after PDM capture RMS counts indicate signal magnitude; calibrated sound pressure is needed for dB SPL. External capacitive keypad UART example: GP20 TX / GP21 RX Encoded key byte Decode the module-specific byte into a key character.
Board mappings and examples: Chapter 3: System Inputs overview . Optical sensor behaviour: Adafruit APDS9960 API .
Explore the information path Select an input Push button Humidity Proximity Sound Keypad
Figure 3.13. Input-to-information explorer. Example readings are illustrative, not live hardware measurements.
From a level to an event Level detection asks whether an input is active now. Edge detection identifies a change between observations. For an active-low button, HIGH → LOW is a press; LOW → HIGH is a release. Debounce first when one physical action must produce one event.
Observation Raw GP0 Pressed = not raw Result Released 1 / True False No press event New press 0 / False True One press event Still held 0 / False True Still active; no new press edge Released again 1 / True False Release event; ready for another press
Timing and reliable interpretation Polling repeatedly samples an input. With ideal evenly spaced samples separated by Ts , recognition of a persistent new state takes up to about Ts , before debouncing and processing. Shorter pulses can fall entirely between samples. A buffered event source can preserve transitions until read, but buffers are finite.
Ts sampling interval (s) fs sampling frequency (samples/s) Ts = 10 ms Ts = 0.010 s fs = 1 ÷ Ts fs = 1 ÷ 0.010 s fs = 100 samples/s
A 4 ms pulse may fall between samples and be missed. Serial bytes require protocol decoding rather than a single switch-state reading.
Revisit 3.2 Input operations for voltage thresholds, floating pins, polling and bounce graphs. Digital communication does not eliminate noise, invalid packets or sensor measurement error.
Guided analysis A button counter increases continuously while the button is held. Diagnose the cause. The program increments whenever the active level is sampled. It needs a debounced press transition, not repeated active-level checks. Increasing the loop delay only changes how quickly the incorrect count grows.
The humidity changes continuously, but the sensor is connected to SDA/SCL. Classify the input. Humidity is a continuous physical quantity. The AHT20 converts it internally and sends digital data over I²C. The RP2040 requires an I²C driver, not an ADC conversion on SDA.
Continue the lesson 3.4.1 Push button : one action, one event, one output change. 3.4.2 Keypad : matrix scanning and encoded external-keypad data.
CHAPTER 3 / SYSTEM INPUTS
3.4.1 Push button Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Trace raw levels, debounced transitions and output state; diagnose repeated counts and missed presses.
Formal programming and hardware assessment under CLO2 follows Chapter 5.
3.4.1.1 Definition and EDU PICO connections Push button is a momentary switch whose contacts change state while operated. A normally open contact is open when released. The EDU PICO user buttons are active-low: Button A uses GP0 and Button B uses GP1. Do not confuse these with BOOTSEL.
Condition GPIO voltage (ideal) Raw value Meaning Released, pulled up 3.3 V True / 1 Not pressed Pressed, connected to GND 0 V False / 0 Pressed
The pull-up prevents a floating released input. Use pressed = not button.value to express the user action. Review the existing 1.2.5 input circuits and 3.2 debounce explanation before tracing this application.
3.4.1.2 Interactive press event and output response Toggle means invert a stored output state once per accepted press. It differs from a momentary output that follows the held button. Click Press/Release to hold each state for explanation; “Sample held state” represents another loop iteration.
Press Button A Sample held state Reset
Figure 3.14. GP0 press-event demonstration. Each click represents an already debounced transition. Sampling a held state does not generate another press. Pixel 0 is controlled through GP14/NeoPixel, not wired directly to GP0.
3.4.1.3 Trace the algorithm before reading the code Debouncing accepts a new switch state only after the chosen filter criterion is met. Here the candidate state must remain unchanged for 20 ms, checked by a regularly running loop. This is a teaching choice, not a universal switch specification.
Read GP0 and current time Track candidate unchanged ≥ 20 ms Accept changed stable state If new press: count + toggle → → → Repeat the loop; a release updates state but does not toggle. Figure 3.15. Button-processing flow. If the candidate is still changing or the accepted state has not changed, continue sampling without an event.
With an ideal 5 ms loop and a 20 ms stable-time filter, an isolated transition is typically accepted about 20–25 ms after it occurs. Bounce restarts the stability timer; slow loop work adds delay.
3.4.1.4 CircuitPython: count presses and toggle pixel 0 Run as a standalone code.py. Install the matching neopixel library in CIRCUITPY/lib. Only pixel 0 changes; the remaining four start OFF. This example deliberately uses software state variables so every decision can be traced.
import time
import board
import digitalio
import neopixel
button = digitalio.DigitalInOut(board.GP0)
button.switch_to_input(pull=digitalio.Pull.UP)
pixels = neopixel.NeoPixel(board.GP14, 5, brightness=0.1,
auto_write=False, pixel_order=neopixel.GRB)
pixels.fill((0, 0, 0))
pixels.show()
candidate = button.value
stable = candidate
changed_at = time.monotonic()
on = False
count = 0
try:
while True:
raw = button.value
now = time.monotonic()
if raw != candidate:
candidate = raw
changed_at = now
if candidate != stable and now - changed_at >= 0.020:
stable = candidate
if not stable: # New debounced active-low press
count += 1
on = not on
pixels[0] = (0, 255, 0) if on else (0, 0, 0)
pixels.show()
print("Presses:", count, "Pixel 0:", on)
time.sleep(0.005)
finally:
pixels.fill((0, 0, 0))
pixels.show()
pixels.deinit()
button.deinit()Element Purpose candidate / changed_atRecord the latest raw state and when it last changed. stableStore the previously accepted state; prevents repeated events while held. not stableAccept the press edge; release only rearms the next press. on = not onInvert the remembered output, independent of how long the button remains pressed. pixels[0] / show()Update the first pixel and transmit the buffered colour data. finally / deinit()Turn pixels off and release resources when execution exits the try block.
The initial raw state becomes the initial stable state. A button held at startup is not counted until released and pressed again. Do not configure GP0 simultaneously through another input object. For reusable event scanning, CircuitPython also provides keypad.Keys ; its name covers independent buttons as well as keypads.
API references: digitalio and NeoPixel .
3.4.1.5 Tutorial and troubleshooting Trace press → held → release → press, starting with pixel 0 OFF. First press: count 1, pixel ON. Held: count remains 1. Release: count remains 1, pixel stays ON. Second press: count 2, pixel OFF. Compare with a momentary lamp, which would turn OFF on release.
One press causes several increments. Identify two checks. Check whether counting uses a transition rather than every active sample. Then check whether contact bounce is filtered before accepting transitions. A longer sleep alone does not guarantee one event per action.
Why might a short tap be ignored? A tap shorter than the acceptance interval may never establish a stable press. Blocking code may also stop the loop observing it. Choose and test the sampling/filter timing for the intended interaction.
CHAPTER 3 / SYSTEM INPUTS
3.4.2 Keypad Lesson developed RP2040 · CircuitPython · EDU PICO
Learning focus · CLO1 (C4, PLO2) Analyse matrix scans and serial key codes, distinguish their wiring, and diagnose ambiguous or invalid input.
Formal programming and hardware assessment under CLO2 follows Chapter 5.
3.4.2.1 Definition and two different interfaces Keypad is an arrangement of keys used to enter symbols or commands. A matrix keypad connects switches between rows and columns. A capacitive keypad detects touch through a change in capacitance; its controller may send decoded information over a bus.
Type What RP2040 receives How to read it Raw mechanical 4 × 3 matrix Four row and three column connections Scan connections to identify a switch. Twelve keys need 4 + 3 = 7 signal pins rather than twelve independent inputs. External ATtiny1616 capacitive module used in course examples UART key codes Receive and decode module bytes. The module handles touch sensing. An I²C touch-controller variant I²C registers or events Use its actual device protocol and driver; UART code is not interchangeable.
The keypad is external extension hardware , not an onboard EDU PICO component. First learn matrix scanning conceptually, then use the separately identified UART module example below. A raw matrix has no UART TX pin.
3.4.2.2 Interactive row-and-column scan Scanning tests one row at a time and observes the columns. In this illustrative active-low scheme, columns have pull-ups, the selected row is driven LOW, and inactive rows are high-impedance inputs. A closed switch connects its column to the selected LOW row. Avoid driving inactive rows HIGH in a simple multi-key matrix, which can cause output contention.
Click one key to hold it, then step through the rows. This single-key demonstration excludes bounce and ghosting. Row/column numbers below are zero-based.
1 2 3 4 5 6 7 8 9 * 0 #
Scan next row Release / reset
Figure 3.16. Four-row, three-column matrix scan. A filled switch marker is closed; other switches are open. Highlighted conductors and column bits identify a held key only during its row's scan.
i zero-based key index row zero-based row index column zero-based column index Ncolumns number of keypad columns Nrows number of scanned keypad rows trow dwell time per row (s) Tscan duration of a full keypad scan (s) fscan complete scans per second i = row × Ncolumns + column i = 2 × 3 + 1 i = 7 Tscan = Nrows × trow Tscan = 4 × 0.002 s Tscan = 0.008 s fscan = 1 ÷ Tscan fscan = 125 scans/s
Index 7 selects key 8 in the shown lookup list. The ideal scan rate excludes debounce and software overhead.
Worked examples — keypad scanning Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
i zero-based key index row zero-based row index column zero-based column index Ncolumns number of keypad columns Nrows number of scanned keypad rows trow dwell time per row (s) Tscan duration of a full keypad scan (s) fscan complete scans per second Example 1 — Find the lookup index for zero-based row 2 and column 1 in a three-column keypad Given: Zero-based row 2, column 1; three columns.
i = row × Ncolumns + column i = 2 × 3 + 1 i = 7
Interpretation: Index 7 selects the eighth list item, key 8 in the shown layout.
Example 2 — Find the complete scan time and scan rate for four rows with a 2 ms dwell per row Given: Four rows; dwell 2 ms per row.
Tscan = Nrows × trow Tscan = 4 × 2 ms Tscan = 8 ms fscan = 1 ÷ Tscan fscan = 1 ÷ 0.008 s fscan = 125 scans/s
Interpretation: This ideal rate excludes debounce and software overhead.
3.4.2.3 Scanning algorithm and ambiguous presses Repeat for each row:
Put all row pins in high-impedance input mode
Drive only the selected row LOW
Allow signals to settle
Read all pulled-up column inputs
A LOW column identifies a closed switch in this row
Release the selected row, debounce complete key states,
and emit a new press event only when the accepted state changesThis is algorithmic pseudocode, not a ready-to-run EDU PICO pin assignment. A real matrix requires a checked connector pinout and seven available GPIOs; the course board already allocates many pins to peripherals. CircuitPython's keypad.KeyMatrix can manage scanning and event delivery for a correctly wired matrix.
Ghosting means reporting a key that is not physically pressed because several closed switches form an unintended electrical path. In a diode-free matrix, pressing three corners of a rectangle can make the fourth appear closed. For example, “1”, “2” and “4” can create an apparent “5”. Suitable per-key diodes or a deliberately restricted key policy are needed when multiple simultaneous keys must be handled reliably. Debouncing alone does not remove this electrical ambiguity.
3.4.2.4 EDU PICO connection: external UART keypad Module terminal EDU PICO connection Purpose TX GP21 / RX Keypad → RP2040 data RX GP20 / TX RP2040 → keypad data, if required VCC 3.3 V Supply for the documented compatible module GND GND Shared voltage reference
Shared-pin check: GP21 also controls the onboard buzzer circuit. Follow the board’s documented buzzer isolation/disable arrangement before UART use; if the circuit cannot be isolated, select a verified alternative UART connection. Stopping the buzzer program alone does not disconnect its hardware. Do not allocate the same GPIO to UART and PWM simultaneously.
The course example uses the Seeed ATtiny1616 module at 9600 baud. Its bytes 0xE1–0xEC map in order to 123456789*0#; these are not ASCII digit bytes. The module protocol does not provide a continuous GPIO pressed/released level to this program. Manufacturer module reference ; M11: Capacitive keypad wiring and example .
3.4.2.5 Interactive byte decoding and serial timing UART frame is the timed bit sequence used to transmit a character. For the 8N1 setting below it contains one LOW start bit, eight data bits sent least-significant bit first, and one HIGH stop bit. Idle is HIGH; there is no separate clock wire.
Received key code 0xE1 · 1 0xE2 · 2 0xE3 · 3 0xE4 · 4 0xE5 · 5 0xE6 · 6 0xE7 · 7 0xE8 · 8 0xE9 · 9 0xEA · * 0xEB · 0 0xEC · # 0x00 · unknown Receive byte Clear history
Virtual received-character history · last 8 characters —
Figure 3.17. UART key-byte decoder. Changing the selector previews a frame; “Receive byte” appends a recognised character. Unknown bytes are rejected. This demonstrates decoding, not the module's touch or repeat timing.T period of one cycle (s unless another time unit is stated) fbus bus clock or serial bit rate (Hz or bit/s as stated) Nbits transmitted bits per frame or transfer tframe frame or transfer time (s) T = 1 ÷ fbus T = 1 ÷ 9600 s T ≈ 104.17 µs Nbits = 1 + 8 + 1 Nbits = 10 tframe = Nbits ÷ fbus tframe = 10 ÷ 9600 s tframe ≈ 1.042 ms
Transmission time excludes keypad sensing, application processing and display latency.
Worked examples — UART frame timing Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
fbus bus clock or serial bit rate (Hz or bit/s as stated) Nbits transmitted bits per frame or transfer T period of one cycle (s unless another time unit is stated) tframe frame or transfer time (s) Example 1 — Find one UART bit interval given a rate of 9600 bit/s Given: UART rate 9600 bit/s.
T = 1 ÷ fbus T = 1 ÷ 9600 s T ≈ 104.167 µs
Interpretation: UART sends one binary bit in each bit interval.
Example 2 — Find the transmission time of one 8N1 UART frame at 9600 bit/s Given: One start bit, eight data bits, one stop bit; rate 9600 bit/s.
Nbits = 1 + 8 + 1 Nbits = 10 tframe = Nbits ÷ fbus tframe = 10 ÷ 9600 s tframe ≈ 1.04167 ms
Interpretation: This is wire transmission time, excluding keypad sensing, software and display latency.
3.4.2.6 CircuitPython: validate a byte before using it import time
import board
import busio
KEYS = "123456789*0#"
history = ""
# Use only after resolving the GP21 buzzer hardware conflict.
with busio.UART(tx=board.GP20, rx=board.GP21,
baudrate=9600, bits=8, parity=None, stop=1,
timeout=0.01) as uart:
while True:
packet = uart.read(16)
if packet:
for value in packet:
if 0xE1 <= value <= 0xEC:
key = KEYS[value - 0xE1]
history = (history + key)[-8:]
print("Key:", key, "History:", history)
else:
print("Ignored byte: 0x{:02X}".format(value))
time.sleep(0.005)Code element Meaning tx / rxPins are named from the RP2040 perspective; cross TX to the other device’s RX. baudrate=9600, bits=8, parity=None, stop=1Agree on 9600 bit/s and an 8N1 frame. timeout=0.01 / read(16)Wait is limited by the read timeout; read returns up to 16 bytes, or None when none arrive. for value in packetProcess every received byte. A read can contain more than one key code. value - 0xE1Convert a validated code to a zero-based index. 0xE8 − 0xE1 = 7, selecting “8”. [-8:]Keep only the latest eight characters. withRelease UART resources when leaving the block.
Do not use chr(value) as a substitute for this lookup: the module codes are not ASCII. Repeated valid bytes are repeated received codes; this example does not invent release events or guarantee one byte per physical touch. CircuitPython busio reference .
3.4.2.7 Tutorial and fault analysis Decode the sequence 0xE1, 0xE8, 0x00, 0xEC. The recognised characters are “1”, “8” and “#”; the history becomes “18#”. The unsupported 0x00 is reported and ignored rather than indexing outside the intended mapping.
A raw matrix works for one key but reports extra keys during a chord. Consider ghosting and the presence/orientation of isolation diodes. Also check that inactive rows are not driven against the selected row. Increasing debounce time does not repair an unwanted current path.
A UART keypad produces no useful characters. Check the exact module model, crossed TX/RX, common ground, supply and logic compatibility, baud/frame settings and GP21 hardware sharing. Print raw hexadecimal bytes first. A matrix or I²C module cannot use this UART decoder.
CHAPTER 04
Software Components YOUR LEARNING GOALS
Chapter 4 learning outcomes By the end of this chapter, students should be able to:
Explain the CircuitPython runtime and trace the structure of a microcontroller application. Use variables, data types, operators, decisions, loops, and collections in CircuitPython programs. Explain functions, objects, hardware constructors, timing, exceptions, and cleanup in the EDU PICO examples. Relate the programming syntax to the source 18-module sequence, mini-project, interactive concept laboratory, and practice tasks. Select a subtopic to view its planned coverage.
15 syntax lessons in 6 groups Outline ready · Lessons to follow
4.1 Introduction 4.2 Getting started and core syntax 4.2.1 What is CircuitPython? 4.2.2 Program structure, comments, and imports 4.2.3 Variables, constants, and data types 4.2.4 Operators and calculations 4.3 Decisions, repetition, and collections 4.3.1 Decisions with if, elif, and else 4.3.2 Switch choices in CircuitPython 4.3.3 Repetition with while and for loops 4.3.4 Lists, Tuples, Dictionaries and Typed Arrays 4.4 Functions, hardware access, and reliability 4.4.1 Functions, parameters, return values, and scope 4.4.2 Modules, objects, properties, and methods 4.4.3 Timing: blocking and non-blocking programs 4.4.4 Errors, exceptions, and cleanup 4.4.5 Complete syntax used by the 18 hardware modules 4.5 Integrated mini-project 4.5.1 Combined mini-project: adjustable LED level 4.6 Interactive concept laboratory 4.6.1 Interactive concept laboratory 4.7 Practice and quick reference 4.7.1 Practice tasks and quick reference CHAPTER 4 / SOFTWARE COMPONENTS
4.1 Introduction Lesson developed RP2040 · CircuitPython · EDU PICO
Hardware supplies the capabilities. Software determines when to read, what a reading means and how the system should respond.
Learning focus · CLO1 (C4, PLO2) Distinguish application, library, runtime and hardware roles; trace instructions into an observable output; analyse why actual behaviour may differ from the requirement.
This lesson builds on Chapters 2–3. Formal CLO2 practical work remains after Chapter 5.
4.1.1 Definitions: software, firmware and application Software is the set of instructions and supporting data that gives a computing system its behaviour. The same hardware can perform different tasks when its program changes.
Firmware Software closely associated with a device’s operation, normally stored in non-volatile memory. It can be updated when the device supports an update process.
Application program The code that implements the required task: for example, reading a knob and selecting an LED colour. Our application is usually saved as code.py.
Runtime The execution environment that runs application code and supplies services such as objects, memory management and hardware access. Here it is provided by CircuitPython firmware.
These terms describe roles rather than mutually exclusive categories. CircuitPython firmware and the application are both software; an embedded application may also be called firmware in other development workflows. In this course, distinguish the installed CircuitPython firmware from the editable Python application.
Component Example in this course Role Development environment Thonny on the computer Edit files, view output and diagnose errors; see 1.3 . Application code.py on CIRCUITPYDefine the system’s required behaviour. Library / module neopixel, analogioProvide reusable operations; some modules are built into firmware, while others are installed in lib. Runtime firmware CircuitPython build for the board Execute the application and provide native hardware services. Hardware RP2040, ADC, GPIO and EDU PICO devices Acquire signals, execute machine instructions and produce physical outputs.
4.1.2 How a Python instruction reaches hardware API (application programming interface) is the set of named operations a program uses to access a service. A driver translates device operations into the communication that a particular device needs. For example, the NeoPixel driver turns colour requests into data for the WS2812 chain.
Explore a layer Application Library / API Runtime / native services Hardware
Figure 4.1. Software-to-hardware layers. Arrows show dependency, not four equal-duration CPU instructions. Input information travels back to the application through the same services.The RP2040 CPU executes machine instructions. CircuitPython handles Python source and its internal executable representation, then calls native services when required. A Python line is not one CPU clock cycle, and a 125 MHz processor clock does not mean 125 million Python loop iterations per second.
Runtime and native-module organisation: CircuitPython overview . Library conventions: CircuitPython design guide .
4.1.3 Startup, files and working memory Non-volatile storage retains contents without power; RAM holds the working state while the program runs. Saving a file and changing a variable are different operations.
Item Where / when it is used Effect of restart CircuitPython firmware and saved files Board flash storage; CIRCUITPY exposes the user filesystem Normally persist; a firmware replacement or storage erase is a separate operation. boot.py (optional)Startup configuration before normal workflows Not required for this example; it is not the repeating application loop. code.pyMain application after normal startup or reload Runs again from its initialisation. Variables, sampled readings and object state Working RAM Recreated by the program; not automatically saved to a file. lib/Installed support libraries Use versions compatible with the installed CircuitPython release.
Power / reset Normal boot CircuitPython starts Optional boot.py Run code.py Import + initialise Application loop Read → decide → act → → → A repeating loop is written by the programmer; it is not created automatically. Figure 4.2. Simplified normal startup path. Safe mode and error recovery are outside this diagram.On the usual USB workflow, saving application changes normally triggers an automatic reload when enabled. Reloading is not the same as reinstalling CircuitPython firmware. A board with a saved program and suitable power can run without Thonny remaining open. See Adafruit’s editing and reload guide .
4.1.4 From a requirement to an algorithm Requirement states the behaviour the system must provide. An algorithm is the ordered method that achieves it, independent of the programming-language syntax.
Worked requirement: Read the EDU PICO potentiometer on GP28. Show green on pixel 0 when the reported knob percentage is at least 50%; otherwise show red. Update repeatedly. Pixels 1–4 remain OFF.
Set up the ADC input and five-pixel output once. Capture one input reading. Calculate percentage from that captured reading. Compare the percentage with 50. Choose green or red, then transmit the colour to the LED chain. Wait briefly and repeat from the input read. This previews three programming building blocks: sequence (ordered steps), selection (choose a branch), and iteration (repeat). The lesson focuses on how software coordinates the EDU PICO’s inputs and outputs.
4.1.5 Interactive program trace: input → decision → output Program trace follows execution step by step, recording how values and outputs change. Select an input, then advance one stage. Try changing the input after the Read stage: the stored reading should remain unchanged until the next read.
Fixed threshold: 50% · THRESHOLD = 50.0 At or above 50%: execute the if branch → GREEN. Below 50%: execute the else branch → RED.
Simulated 12-bit ADC code
Execute next stage Finish this cycle Reset trace
Working value Current state Fixed threshold 50.0% Captured API reading — Calculated percentage — Selected colour in buffer OFF Physical pixel 0 OFF
Figure 4.3. Manual execution trace of the example below. The 12-bit ADC code is expanded to the CircuitPython API range using the same RP2040 model as 3.3.1 . This simulation omits noise and executes stages on demand; it does not model real-time instruction speed.Observe two separate updates: assigning pixels[0] changes the software buffer when auto_write=False; pixels.show() sends it to the hardware. Red means “below threshold”, not OFF. Noise near the threshold can cause flickering; this introductory example has no hysteresis.
4.1.6 Complete CircuitPython example and technical interpretation Save as code.py on the board. The analogio, board and time modules are supplied by the appropriate firmware; install a compatible neopixel library in lib. Run this standalone so other programs do not claim GP28 or GP14.
import time
import board
import analogio
import neopixel
THRESHOLD = 50.0
pot = analogio.AnalogIn(board.GP28)
pixels = neopixel.NeoPixel(board.GP14, 5, brightness=0.1,
auto_write=False, pixel_order=neopixel.GRB)
pixels.fill((0, 0, 0))
pixels.show()
try:
while True:
reading = pot.value
percent = reading * 100 / 65535
if percent >= THRESHOLD:
pixels[0] = (0, 255, 0)
else:
pixels[0] = (255, 0, 0)
pixels.show()
time.sleep(0.1)
finally:
pixels.fill((0, 0, 0))
pixels.show()
pixels.deinit()
pot.deinit()Instruction or construct Software effect Hardware consequence import and constructorsLoad dependencies and create input/output objects Initialise the interfaces; perform setup outside the repeating loop. reading = pot.valueStore one returned measurement Read the GP28 ADC input. Later calculations use this stored value. percent = reading * 100 / 65535Calculate a new number No output changes merely because arithmetic runs. if … elseExecute one colour-selection branch Specify the desired output based on the requirement. pixels[0] = …Modify the first pixel’s buffered colour Wait for show() because auto_write is disabled. pixels.show()Transfer the buffered pixel data Update the WS2812 chain using GP14. time.sleep(0.1)Pause this application’s execution for approximately 100 ms No fresh input read occurs in this loop during the pause; the existing LED colour remains. finallyRun cleanup on exit from the try block Request LEDs OFF and release objects; not a guarantee against abrupt power loss.
Precision reminder: the API reports values over 0–65535, but this does not turn the RP2040’s 12-bit ADC into a 16-bit converter. Review 3.3.1 for the resolution distinction. The example uses a percentage threshold to teach software flow, not an independently calibrated position measurement.
API references: AnalogIn and NeoPixel .
Worked examples — interpret a scaled input Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
r CircuitPython ADC reading on the 0–65,535 API scale p percentage on a 0–100 scale (%) Tloop loop duration Twork processing duration Tsleep sleep duration fs sampling frequency (samples/s) Example 1 — Find the percentage and selected colour for ADC API reading 16,388 on a 0–65,535 scale using the program thresholds Given: ADC API reading 16,388.
p = 100 × r ÷ 65,535 p = 100 × 16,388 ÷ 65,535 p ≈ 25.0065%
Interpretation: This selects RED under the example program’s thresholds.
Example 2 — Find the percentage and selected colour for ADC API reading 49,164 on a 0–65,535 scale using the program thresholds Given: ADC API reading 49,164.
p = 100 × r ÷ 65,535 p = 100 × 49,164 ÷ 65,535 p ≈ 75.0198%
Interpretation: This selects GREEN under the example program’s thresholds.
Example 3 — Find loop period and update rate given 10 ms of work followed by 100 ms of sleep Given: Illustrative work time 0.010 s; program sleep 0.100 s.
Tloop = Twork + Tsleep Tloop = 0.010 s + 0.100 s Tloop = 0.110 s fs = 1 ÷ Tloop fs = 1 ÷ 0.110 s fs ≈ 9.09 samples/s
Interpretation: The sleep interval alone does not guarantee an exact 10 Hz update rate.
4.1.7 Trace, diagnose and verify Debugging is finding and correcting the cause of behaviour that differs from the requirement. Verification checks the result against that requirement, including boundary conditions.
Fault category Example symptom Useful first check Syntax / indentation The interpreter reports a syntax or indentation error Check the reported line, colons and block indentation. Runtime / dependency The program stops during an import or hardware setup Read the traceback; check the library name/version and pin ownership. Logic Code runs but green appears below the threshold Trace the comparison and the two branch assignments against the requirement. Timing / sampling An input change seems to have a delayed effect Identify when the last reading was captured and what work delays the next read. Interface / output update The buffered colour changes but the LED does not Check show(), the pin mapping, power and the physical connection.
Tutorial 1 · Move the knob after Read but before Decide. Which input does the decision use? The stored reading from Read. The expression does not continuously monitor the pin. The next cycle captures the new input. Use Figure 4.3 to demonstrate this separation.
Tutorial 2 · Compare ADC codes 2047 and 2048 at the 50% boundary. The API model produces 32759 (about 49.987%) and 32776 (about 50.013%). Therefore 2047 selects red, and 2048 selects green. The exact mathematical value 50% need not be one of the available ADC readings.
Tutorial 3 · A restart returns a counter to zero even though code.py is still saved. The saved program remains in non-volatile storage. A runtime counter is working state in RAM and is initialised again when the program starts. Persistence requires an explicit storage design.
Tutorial 4 · Removing show() leaves a stale physical colour. Explain why. With auto_write=False, selecting an RGB tuple updates only the software buffer. The application must transfer it with show(). A correct comparison does not by itself perform the physical output operation.
4.1.8 Check your understanding · six MCQs CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.2 Getting started and core syntax Programming fundamentals RP2040 · CircuitPython · EDU PICO
Learning goal Understand what CircuitPython does, how a program is organized, how values are represented, and how calculations work.
The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.
What is CircuitPython? Program structure, comments, and imports Variables, constants, and data types Operators and calculations CHAPTER 4 / SUBTOPIC 4.2.1
4.2.1 What is CircuitPython? Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition CircuitPython is a Python-based runtime for supported microcontroller boards; it runs an application and provides access to board hardware.
Source topic: 1. What is CircuitPython?
Learning goal Understand how a CircuitPython program runs on the EDU PICO.
Syntax: smallest CircuitPython program
print (VALUE)
print ("Hello, EDU PICO!" )
CircuitPython is a version of Python designed for microcontroller boards. When a file named code.py is saved on the CIRCUITPY drive, the board automatically runs it.
Connect the EDU PICO by USB.
Copy the required libraries into CIRCUITPY/lib.
Rename one tutorial file to code.py.
Save it to CIRCUITPY.
Use the serial console to read print() output and errors.
print ("Hello, EDU PICO!" )
Hello, EDU PICO!
Hardware rule EDU PICO GPIO uses 3.3 V logic. Never connect a motor directly to a GPIO pin, and never apply 5 V to a GPIO input.
Verified 18-module practical sequence
The numbered Python files now follow the working demonstration program exactly. Use the left menu to open any module.
Module Hardware Verified GPIO / bus
01 Push buttons A GP0, B GP1
02 Five WS2812 LEDs GP14
03 AHT20 temperature/humidity I2C SDA GP4, SCL GP5
04 APDS9960 proximity I2C SDA GP4, SCL GP5
05 APDS9960 light I2C SDA GP4, SCL GP5
06 APDS9960 gesture I2C SDA GP4, SCL GP5
07 APDS9960 colour I2C SDA GP4, SCL GP5
08 PDM microphone Clock GP3, data GP2
09 Potentiometer ADC GP28
10 Audio and buzzer Audio GP20, buzzer GP21
11 SD card MISO16, CS17, SCK18, MOSI19
12 Flash-log switch GP15
13 Servo and potentiometer Servo GP6, ADC GP28
14 Two DC-motor channels GP10–GP13
15 USB power relay GP22
16 Capacitive keypad Pico TX GP20, RX GP21
17 28BYJ-48 stepper GP26, GP27, GP8, GP7
18 TM1650 four-digit display I2C SDA GP4, SCL GP5
Installation Copy the complete Tutorials/lib directory to CIRCUITPY/lib. The included libraries are the verified CircuitPython 10 set used by these lessons.
CHAPTER 4 / SUBTOPIC 4.2.2
4.2.2 Program structure, comments, and imports Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition Program structure is the organization of imports, hardware setup, reusable functions, and the main application flow.
Source topic: 2. Program structure, comments, and imports
Learning goal Recognise the main parts of a CircuitPython program.
Syntax: imports, comments, and blocks
import MODULE
from MODULE import NAME
while CONDITION:
INDENTED_STATEMENT
import time
import board
import digitalio
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT
while True:
led.value = True
time.sleep(0.5)
led.value = False
time.sleep(0.5)
import loads a module.
A comment begins with # and is ignored by the board.
Indentation defines which statements belong inside a loop, function, or decision.
Python is case-sensitive: True is valid, but true is not.
Important Use four spaces for each indentation level. Incorrect indentation causes an IndentationError.
CHAPTER 4 / SUBTOPIC 4.2.3
4.2.3 Variables, constants, and data types Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A variable is a name bound to a value; a data type describes the value and its suitable operations.
Source topic: 3. Variables, constants, and data types
Learning goal Store values and choose suitable data types.
Syntax: variable assignment
variable_name = VALUE
CONSTANT_NAME = VALUE
variable_name = variable_name + CHANGE
A variable is a named storage location. Python creates it when a value is assigned with =; no separate declaration keyword is required.
student_name = "Aisyah"
counter = 0
voltage = 2.75
button_pressed = False
counter = counter + 1
print (student_name, counter, voltage, button_pressed)
Constants are values that should not change. Python does not enforce constants, so uppercase names communicate the intention:
LED_PIN = board.GP14
NUMBER_OF_LEDS = 5
UPDATE_INTERVAL = 0.2
Guidelines for naming variables and constants
Choose a descriptive name that explains the value's purpose, such as motor_speed or sensor_voltage, instead of a vague name such as x (except for a short loop counter).
For ordinary variables, use lowercase words separated by underscores: button_pressed, motor_speed.
For values intended to remain fixed, use uppercase words separated by underscores: ADC_MAX_VALUE, LED_PIN. This is a convention; Python does not prevent reassignment.
An identifier must start with a letter or underscore; later characters may also include digits. Names are case-sensitive, so motor_speed and Motor_Speed are different names.
Do not use spaces, hyphens, or a leading digit. For example, motor speed, motor-speed, and 2nd_reading are invalid identifiers.
Avoid Python keywords such as if, for, and class, because Python reserves them for its syntax.
Good naming pattern: temperature_c = 26.5 is a changeable reading; MAX_TEMPERATURE_C = 40.0 communicates a fixed limit.
Type Example Use in tutorials
int65535ADC values, counters, PWM duty cycle
float3.3Voltage, temperature, time
str"Clockwise"Messages and display text
boolTrueButton and output states
NoneNoneNo value or no event
Try it Change voltage to 3.3, add another variable called percentage, and print both values.
CHAPTER 4 / SUBTOPIC 4.2.4
4.2.4 Operators and calculations Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition An operator performs arithmetic, comparison, Boolean, or membership operations on values.
Source topic: 4. Operators and calculations
Learning goal Calculate sensor values and compare program states.
Syntax: arithmetic, comparison, and logic
result = LEFT_VALUE + RIGHT_VALUE
result = LEFT_VALUE - RIGHT_VALUE
result = LEFT_VALUE * RIGHT_VALUE
result = LEFT_VALUE / RIGHT_VALUE
comparison = LEFT_VALUE == RIGHT_VALUE
combined = CONDITION_1 and CONDITION_2
alternative = CONDITION_1 or CONDITION_2
opposite = not CONDITION
Arithmetic
+ add, - subtract, * multiply, / divide, // whole-number divide, % remainder, ** power.
Comparison and logic
==, !=, <, >, <=, >=, together with and, or, and not.
Example: convert an ADC reading
adc = 32768
voltage = adc * 3.3 / 65535
percentage = adc * 100 / 65535
print ("Voltage:" , voltage)
print ("Level:" , percentage, "%" )
Voltage: 1.650...
Level: 50.000... %
Assignment versus comparison = stores a value. == asks whether two values are equal.
Open M08: Potentiometer
More operator examples
Arithmetic
print(10 + 3) # 13: addition
print(10 - 3) # 7: subtraction
print(10 * 3) # 30: multiplication
print(10 / 3) # 3.333...: division
print(10 // 3) # 3: floor division
print(10 % 3) # 1: remainder
print(2 ** 3) # 8: power
Floor division rounds down: -10 // 3 is -4. Parentheses clarify calculation order: (3 + 4) * 2 is 14.
Comparison
temperature = 32
print(temperature == 32) # True: equal
print(temperature != 30) # True: not equal
print(temperature > 30) # True: greater than
print(temperature < 30) # False: less than
print(temperature >= 32) # True: greater than or equal
print(temperature <= 35) # True: less than or equal
Comparisons return True or False. Use = to assign and == to compare.
Logic
temperature = 32
fan_enabled = True
emergency = False
print(temperature > 30 and fan_enabled) # True: both
print(temperature >= 35 or emergency) # False: either
print(not emergency) # True: opposite
if temperature > 30 and fan_enabled:
print("Turn on fan")
and needs both conditions; or needs at least one; not reverses a Boolean condition.
Remainder in a loop
for count in range(4):
if count % 2 == 0:
print(count, "even")
else:
print(count, "odd")
The output identifies 0 and 2 as even, and 1 and 3 as odd.
CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.3 Decisions, repetition, and collections Programming fundamentals RP2040 · CircuitPython · EDU PICO
CHAPTER 4 / SUBTOPIC 4.3.1
4.3.1 Decisions with if, elif, and else Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A conditional statement selects a block of code according to one or more Boolean tests.
Source topic: 5. Decisions with if, elif, and else
Learning goal Make the program choose an action based on a condition.
Syntax: if–elif–else
if CONDITION_1:
STATEMENTS_FOR_CONDITION_1
elif CONDITION_2:
STATEMENTS_FOR_CONDITION_2
else :
STATEMENTS_WHEN_FALSE
temperature = 31.5
if temperature >= 35:
print ("Warning: very hot" )
elif temperature >= 28:
print ("Warm" )
else :
print ("Normal" )
Example: active-low button
if button.value == False:
print ("Pressed" )
else :
print ("Released" )
An active-low button reads False when pressed because pressing it connects the input pin to ground.
Open M01: Push buttons
Compact conditional expression
Syntax
value_if_true if condition else value_if_false
Python checks the condition. If it is true, the expression before if becomes the result; otherwise, the expression after else becomes the result. This form produces one value and is useful when choosing between two short results.
Example 1: temperature status
temperature = 31.5
status = "WARNING" if temperature >= 30.00 else "NORMAL"
print(status)
Since 31.5 >= 30.00 is true, status becomes "WARNING". At a temperature below 30.00 °C, it becomes "NORMAL". The same logic in the full block form is:
if temperature >= 30.00:
status = "WARNING"
else:
status = "NORMAL"
Example 2: pass or retry
mark = 68
result = "PASS" if mark >= 50 else "RETRY"
print(result)
Because the mark is at least 50, the expression assigns "PASS" to result.
CHAPTER 4 / SUBTOPIC 4.3.2
4.3.2 Switch choices in CircuitPython Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A switch-like choice selects one response from several alternatives, using if/elif or dictionary lookup.
Source topic: 6. “Switch” choices in CircuitPython
Learning goal Select one action from many choices.
Syntax: switch-compatible alternatives
if selection == VALUE_1:
ACTION_1
elif selection == VALUE_2:
ACTION_2
else :
DEFAULT_ACTION
choices = {
KEY_1: RESULT_1,
KEY_2: RESULT_2,
KEY_3: RESULT_3,
}
result = choices.get(selection, DEFAULT_RESULT)
Traditional C and Arduino programs use switch/case. For compatibility across CircuitPython versions, use if/elif/else or a dictionary. Do not depend on Python's newer match/case syntax unless the installed CircuitPython version explicitly supports it.
Method 1: if/elif
command = "STOP"
if command == "CW" :
print ("Run clockwise" )
elif command == "CCW" :
print ("Run counter-clockwise" )
elif command == "STOP" :
print ("Stop motor" )
else :
print ("Unknown command" )
Method 2: dictionary lookup
The same motor commands can be mapped to messages using a dictionary.
commands = {
"CW": "Run clockwise",
"CCW": "Run counter-clockwise",
"STOP": "Stop motor",
}
command = "STOP"
result = commands.get(command, "Unknown command")
print(result) # Stop motor
get(command, "Unknown command") returns the matching message, or the default if the key is missing.
Use if/elif for different actions or complex conditions; use a dictionary when a key maps directly to a value.
Another dictionary example: capacitive keypad
key_map = {
0xE1: "1" ,
0xE2: "2" ,
0xEA: "*" ,
}
raw_value = 0xE2
key = key_map.get(raw_value, "unknown" )
print (key)
A dictionary is ideal when one input value maps directly to one result, as in the capacitive keypad tutorial.
Open M11: Capacitive keypad CHAPTER 4 / SUBTOPIC 4.3.3
4.3.3 Repetition with while and for loops Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A loop repeats a block while a condition remains true or while it visits items in a sequence.
Source topic: 7. Repetition with while and for loops
Learning goal Repeat continuously or repeat a known number of times.
Syntax: while, for, and range
while CONDITION:
REPEATED_STATEMENTS
for item in COLLECTION:
STATEMENTS_USING_ITEM
for number in range(START, STOP, STEP):
STATEMENTS_USING_NUMBER
while loop: repeat while a condition is true
while True:
print ("This runs forever" )
time.sleep(1)
for loop: visit each item
colours = ("red" , "green" , "blue" )
for colour in colours:
print (colour)
range(): generate number sequences
for number in range(5):
print (number)
for angle in range(0, 181, 10):
set_angle(angle)
Avoid accidental busy loops A fast infinite loop can make output unreadable and waste processing time. Add a suitable time.sleep() or event schedule.
Open M14: Servo motor Six-question self-check Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.
1. What values does range(4) generate? Bloom: Remember
1, 2, 3, 4 0, 1, 2, 3 0, 1, 2, 3, 4 Only 4
2. When does a while loop test its condition? Bloom: Understand
Before each iteration Only after the loop finishes Once when importing Never
3. What is a common cause of an unintended infinite loop? Bloom: Analyze
The condition never changes toward False Using range Using a comment Importing board
4. Which loop suits processing every item in a list? Bloom: Apply
for item in items if item in items return items import items
5. Why might an embedded main loop use while True? Bloom: Understand
The application should continuously read inputs and update outputs It means the program runs once It ends the board power It imports libraries
6. What does `break` do in a loop? Bloom: Remember
Exit the nearest loop Skip one iteration only Return from every function Restart the loop
Check answers Reset Not checked yet
CHAPTER 4 / SUBTOPIC 4.3.4
4.3.4 Lists, Tuples, Dictionaries and Typed Arrays Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A collection stores multiple related values; its type determines how values are organized and accessed.
Source topic: 8. Arrays and other collections
Learning goal Store multiple related values under one name.
Four ways to store related values Lists can be changed; tuples have fixed items; dictionaries look up values by key; typed arrays store values of one numeric type compactly.
List: changeable values items = [ITEM_1, ITEM_2, ITEM_3]
items[INDEX] = NEW_VALUE
items.append(NEW_VALUE)Square brackets create a list; commas separate items. Positions start at zero. An index in brackets accesses or changes an item; append adds an item at the end.
readings = [20, 22, 25]
readings[1] = 23
readings.append(27)
print(readings[0], readings[-1])
print(readings[1:3])
print(23 in readings)The slice [1:3] includes index 1 but excludes index 3; in checks membership.
Expected output 20 27
[23, 25]
True
Tuple: fixed sequence values = (ITEM_1, ITEM_2, ITEM_3)
value = values[INDEX]Parentheses and commas define a tuple. Access items by zero-based index as with a list, but individual tuple items cannot be reassigned. A one-item tuple needs a trailing comma, for example (1,).
sequence = ((1, 0, 0, 0), (1, 1, 0, 0))
print(sequence[1])
print(sequence[1][0])The outer tuple holds phase tuples; sequence[1][0] selects the first value of the second phase. A fixed sequence is useful for stepper motor phases.
Expected output (1, 1, 0, 0)
1
Dictionary: keys and values mapping = {KEY_1: VALUE_1, KEY_2: VALUE_2}
value = mapping.get(KEY, DEFAULT_VALUE)Braces create a dictionary. Each key is followed by a colon and its value; commas separate pairs. Access a value using its key, not its position. Keys must be unique.
commands = {"CW": "Clockwise", "STOP": "Stop"}
print(commands["CW"])
print(commands.get("CCW", "Unknown"))get(key, default) returns the default when the key is absent. Bracket access to a missing key raises KeyError.
Expected output Clockwise
Unknown
Typed array: compact numeric buffer import array
buffer = array.array(TYPE_CODE, INITIAL_VALUES)Import array first. array.array(typecode, initial_values) creates a changeable sequence of numbers of the specified type. The type code H stores unsigned 16-bit integers, from 0 to 65535.
import array
samples = array.array("H", [0] * 4)
samples[0] = 1200
print(samples[0], len(samples))The expression [0] * 4 creates four initial zeros. Indexing starts at zero. A buffer of 256 H samples uses 512 bytes for sample data, excluding object overhead.
Expected output 1200 4
Choose a list for changing general values, a tuple for a fixed sequence, a dictionary for key-to-value lookup, and a typed array for compact numeric samples.
Open M07: PDM microphone Six-question self-check Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.
1. What is the index of the first item in a Python list? Bloom: Remember
0 1 -1 Depends on list length
2. Which collection is immutable? Bloom: Remember
list tuple dict bytearray
3. What does `value in items` test? Bloom: Understand
Membership List length Type conversion Memory address
4. Which is suitable for a fixed stepper phase sequence? Bloom: Apply
Tuple An uninitialized variable A float A GPIO object
5. What is `values[1:3]` for [4, 8, 12, 16]? Bloom: Apply
[4, 8] [8, 12] [8, 12, 16] [12, 16]
6. Why use a typed array for many same-kind numeric samples? Bloom: Analyze
It stores values compactly using a specified element type It automatically draws a graph It converts every value to text It makes indices start at 1
Check answers Reset Not checked yet
CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.4 Functions, hardware access, and reliability Programming fundamentals RP2040 · CircuitPython · EDU PICO
Learning goal Build reusable code, use CircuitPython hardware objects, manage time, and clean up safely.
The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.
Functions, parameters, return values, and scope Modules, objects, properties, and methods Timing: blocking and non-blocking programs Errors, exceptions, and cleanup Complete syntax used by the 18 hardware modules CHAPTER 4 / SUBTOPIC 4.4.1
4.4.1 Functions, parameters, return values, and scope Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A function is a reusable named block; parameters receive inputs, return values go back to a caller, and scope controls name visibility.
Source topic: 9. Functions, parameters, return values, and scope
Learning goal Organise repeated logic into reusable blocks.
Syntax: define and call a function
def function_name(parameter_1, parameter_2=DEFAULT_VALUE):
STATEMENTS
return RESULT
answer = function_name(ARGUMENT_1, ARGUMENT_2)
def adc_to_voltage(adc_value, reference=3.3):
"""Convert a 16-bit ADC value into volts."""
voltage = adc_value * reference / 65535
return voltage
measured_voltage = adc_to_voltage(32768)
print (measured_voltage)
def creates a function.
adc_value and reference are parameters.
reference=3.3 provides a default argument.
return sends a result back to the caller.
voltage is local: it exists only inside the function.
Function with no return value
def stop_motor():
clockwise.duty_cycle = 0
counter_clockwise.duty_cycle = 0
stop_motor()
Design guideline A function should have one clear job and a meaningful name. This makes hardware programs easier to test and modify.
Open M15: DC motor functions Worked examples: syntax, code and expected output Example 1: function with a parameter and return value Syntax def function_name(parameter):
return result
answer = function_name(argument)Explanation A parameter receives the argument supplied by the caller. return sends the result back; calling the function performs its statements.
Code def double(value):
return value * 2
result = double(6)
print(result)Expected output or behavior 12Example 2: default parameter Syntax def function_name(parameter=default_value):
return resultExplanation A caller may omit a parameter that has a default, or supply another value. Variables created inside a function are local to that function.
Code def adc_to_voltage(raw, reference=3.3):
return raw * reference / 65535
print("{:.2f}".format(adc_to_voltage(32768)))
print("{:.2f}".format(adc_to_voltage(32768, 3.0)))Expected output or behavior 1.65
1.50Example 3: function without a return statement Syntax def function_name():
statements
function_name()Explanation A function can perform an action without explicitly returning a value. Its implicit return value is None.
Code def announce():
print("Ready")
result = announce()
print(result)Expected output or behavior Ready
NoneCHAPTER 4 / SUBTOPIC 4.4.2
4.4.2 Modules, objects, properties, and methods Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A module supplies reusable names; an object groups state and behavior, exposed through attributes, properties, and methods.
Source topic: 10. Modules, objects, properties, and methods
Learning goal Understand the object pattern used by CircuitPython hardware libraries.
Syntax: create and use a hardware object
import MODULE
device = MODULE.CLASS(PIN_OR_BUS)
reading = device.PROPERTY
device.METHOD(ARGUMENTS)
device.deinit()
import board
import analogio
potentiometer = analogio.AnalogIn(board.GP28)
adc = potentiometer.value
potentiometer.deinit()
analogio is a module.
AnalogIn is a class that describes an analogue input.
potentiometer is an object created from that class.
value is a property containing the current ADC reading.
deinit() is a method that releases the hardware resource.
I2C: multiple devices on two wires
import board
import busio
i2c = busio.I2C(board.GP5, board.GP4)
while not i2c.try_lock():
pass
addresses = i2c.scan()
i2c.unlock()
print ([hex(address) for address in addresses])
Typical addresses in these tutorials are OLED 0x3C, AHT20 0x38, APDS9960 0x39, and TM1650 control 0x24.
Open 2.7: OLED and I²C devices Worked examples: syntax, code and expected output Example 1: import a module and call a function Syntax import module_name
result = module_name.function(argument)Explanation A module groups reusable names. The dot selects a name from the module, and parentheses call the function.
Code import math
print(math.sqrt(25))
print(math.ceil(2.3))Expected output or behavior 5.0
3Example 2: create an object and call a method Syntax object_name = ClassName(arguments)
object_name.method(arguments)
value = object_name.propertyExplanation A constructor creates an object. A method performs an operation; a property exposes or updates state. Hardware objects require the appropriate board and wiring.
Code class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
counter = Counter()
counter.increment()
print(counter.count)Expected output or behavior 1Example 3: read and release an analogue input Syntax device = analogio.AnalogIn(pin)
reading = device.value
device.deinit()Explanation Create an analogue input, read its value, and release it when finished. The reading depends on the voltage and hardware.
Code import board
import analogio
sensor = analogio.AnalogIn(board.GP28)
print(sensor.value)
sensor.deinit()Expected output or behavior A numeric ADC reading from 0 to 65535; the actual value depends on the input voltage.
CHAPTER 4 / SUBTOPIC 4.4.3
4.4.3 Timing: blocking and non-blocking programs Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition Timing controls when work occurs; blocking waits pause program flow, while elapsed-time scheduling allows other tasks to run.
Source topic: 11. Timing: blocking and non-blocking programs
Learning goal Choose between simple delays and responsive scheduling.
Syntax: delay and scheduled update
time.sleep(SECONDS)
next_update = time.monotonic()
if time.monotonic() >= next_update:
next_update = time.monotonic() + INTERVAL
SCHEDULED_STATEMENTS
Blocking delay
led.value = True
time.sleep(1)
led.value = False
sleep() is easy to understand, but the program cannot check buttons or sensors during the delay.
Non-blocking schedule
next_update = time.monotonic()
while True:
now = time.monotonic()
if now >= next_update:
next_update = now + 1.0
print ("One-second update" )
time.monotonic() continuously increases while the board is running. It is preferred for measuring intervals because it is not a calendar clock.
Compare the same task: blink and check a button
Assume led is configured as a digital output and button as an active-low input with a pull-up. In both examples the LED changes state every second. The button is pressed when button.value is False.
Blocking version import time
while True:
led.value = not led.value
time.sleep(1.0)
if not button.value:
print("Pressed")
The LED changes, then sleep pauses this Python code path for one second. The button is checked only after the pause, so a short press may be missed.
Non-blocking version import time
next_toggle = time.monotonic() + 1.0
while True:
now = time.monotonic()
if now >= next_toggle:
led.value = not led.value
next_toggle = now + 1.0
if not button.value:
print("Pressed")
First schedule the next toggle for one second from now. On every loop pass, read the current monotonic time and compare it with the deadline. When the deadline is reached, toggle the LED and set a new deadline. The button can be checked on every pass.
The print repeats while the button is held and can slow the loop. A real application can detect the press edge and debounce the button.
Reading the syntax
import time — Import the time module before using its functions.
time.monotonic() — This is a time reading in seconds for measuring elapsed intervals, not a calendar time.
next_toggle = now + 1.0 — Save the time at which the next LED change is due.
now >= next_toggle — Check whether the deadline has been reached or passed.
led.value = not led.value — Reverse the Boolean output state.
next_toggle = now + 1.0 — Schedule the next change one second after this loop observed the deadline.
Timing and responsiveness At about 0 s the first deadline is set for 1 s; around 1 s the LED changes and the next deadline becomes about 2 s. Between these times the loop continues checking the button. Each pass still runs sequentially, so long work elsewhere in the loop can delay the button check or LED update.
Setting the next deadline from now is simple, but late updates accumulate drift. For a steadier schedule, advance the previous deadline by the interval and define how to handle missed intervals.
Hardware PWM can continue its configured waveform during a Python sleep; Python statements and button checks in the paused code path do not run until it resumes.
Challenge Modify the button tutorial so it prints a sensor value every two seconds while still responding immediately to button presses.
Working example: module 17 The reconstructed stepper tutorial advances one due half-step per main-loop pass instead of blocking for all 4096 steps. This is the same responsive pattern used to keep A/B navigation available in the complete demo.
Open M17: Non-blocking stepper Worked examples: syntax, code and expected output Example 1: blocking delay Syntax import time
time.sleep(seconds)Explanation sleep pauses this Python code path for the requested interval. Other statements in the same loop do not run during that pause.
Code import time
print("Start")
time.sleep(1)
print("Done")Expected output or behavior Start
DoneExample 2: check an elapsed-time deadline Syntax deadline = time.monotonic() + interval
if time.monotonic() >= deadline:
action()Explanation monotonic gives elapsed time in seconds. Comparing it with a deadline lets the loop perform other short tasks between updates.
Code import time
deadline = time.monotonic() + 1.0
while time.monotonic() < deadline:
pass
print("One second elapsed")Expected output or behavior One second elapsedExample 3: schedule while checking an input Syntax if now >= next_update:
update_output()
next_update = now + interval
check_input()Explanation The example below is a program fragment: led and button must already be configured, with the button active-low and pulled up. A late loop delays both tasks; detecting press edges and debouncing avoids repeated reports.
Code import time
next_toggle = time.monotonic() + 1.0
while True:
now = time.monotonic()
if now >= next_toggle:
led.value = not led.value
next_toggle = now + 1.0
if not button.value:
print("Pressed")Expected output or behavior The LED toggles approximately every second; Pressed is printed while the button is held.
CHAPTER 4 / SUBTOPIC 4.4.4
4.4.4 Errors, exceptions, and cleanup Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition An exception reports a runtime problem; cleanup restores safe outputs and releases resources after normal completion or failure.
Source topic: 12. Errors, exceptions, and cleanup
Learning goal Read errors and leave hardware in a safe state.
Syntax: try, except, and finally
try :
STATEMENTS_THAT_MAY_FAIL
except ERROR_TYPE as error:
ERROR_HANDLING_STATEMENTS
finally :
CLEANUP_STATEMENTS
Error Common cause
SyntaxErrorMissing punctuation or invalid Python syntax
IndentationErrorBlocks do not use consistent indentation
NameErrorA name is misspelled or used before assignment
ImportErrorA required library is missing
ValueError: incompatible .mpyLibrary bundle and CircuitPython major versions differ
RuntimeErrorHardware is unavailable or incorrectly connected
Safe cleanup pattern
try :
while True:
run_motor("CW" , 50)
except KeyboardInterrupt:
pass
finally :
stop_motor()
clockwise.deinit()
counter_clockwise.deinit()
The finally block runs whether the program completes or fails. It is valuable for switching off motors, LEDs, and buzzers.
Debug the first error A later error can be a consequence of the first failure. Read the complete traceback from its first relevant line.
Worked examples: syntax, code and expected output Example 1: catch a specific exception Syntax try:
statements
except ErrorType as error:
handle_errorExplanation The try block contains operations that may fail. A matching except block handles the named exception; unrelated errors are not silently hidden.
Code try:
number = int("abc")
except ValueError:
print("Invalid number")Expected output or behavior Invalid numberExample 2: cleanup with finally Syntax try:
statements
finally:
cleanup()Explanation finally runs when control leaves the try block, including when a handled exception occurs. Use it to restore safe output states and release initialized hardware resources.
Code try:
print("Start")
raise ValueError("bad input")
except ValueError:
print("Handled")
finally:
print("Cleanup")Expected output or behavior Start
Handled
CleanupExample 3: distinguish normal and invalid input Syntax try:
value = conversion(text)
except ValueError:
handle_invalid_input
else:
use_valueExplanation The else block runs when the try block finishes without an exception. It keeps the successful path separate from error handling.
Code for text in ("42", "abc"):
try:
value = int(text)
except ValueError:
print("Invalid")
else:
print(value)Expected output or behavior 42
InvalidExamples of common error types Run each example separately. The traceback and exact exception name or message can vary by CircuitPython version and hardware.
1. SyntaxError: invalid syntax A missing colon makes this if statement invalid. Python cannot run the program until the syntax is corrected.
Example code temperature = 30
if temperature > 25
print("Warm")Typical error SyntaxError: invalid syntaxHow to address it Add a colon after the condition: if temperature > 25:
2. IndentationError: a missing block indent Statements inside an if block must be indented. IndentationError is a specific kind of SyntaxError.
Example code temperature = 30
if temperature > 25:
print("Warm")Typical error IndentationError: expected an indented blockHow to address it Indent the print statement under the if statement.
3. NameError: an unknown name The name temprature is misspelled; only temperature was defined.
Example code temperature = 30
print(temprature)Typical error NameError: name 'temprature' is not definedHow to address it Use the defined name: print(temperature).
4. ImportError: a missing module This example deliberately imports a fictitious module. A missing library on CIRCUITPY can cause an import error.
Example code import missing_sensor_libraryTypical error ImportError: no module named 'missing_sensor_library'How to address it Check the module name and copy a compatible library to the board when required.
5. ValueError: an unsuitable value The string is valid input to int, but abc cannot be converted into an integer.
Example code text = "abc"
number = int(text)Typical error ValueError: invalid literal for int()How to address it Use numeric text such as "123", or handle ValueError with try and except.
6. RuntimeError: sensor is not ready The program checks whether the sensor is ready. If it is not, the programmer deliberately raises RuntimeError, so the reading statement does not run. This example does not access physical hardware.
Example code sensor_ready = False
if not sensor_ready:
raise RuntimeError("Sensor has not been initialized")
print("Reading sensor")Typical error RuntimeError: Sensor has not been initializedHow to address it Initialize the sensor successfully before attempting to read it. Actual hardware libraries may raise different exceptions depending on the board and operation.
7. OSError: an input/output operation fails Opening a file that does not exist can raise OSError or a more specific subclass. The exact error depends on the runtime and filesystem.
Example code with open("/missing_file.txt", "r") as file:
print(file.read())Typical error OSError: file not foundHow to address it Check the path, filename, storage and access permissions.
8. KeyboardInterrupt: a running program is interrupted Run this loop and send Ctrl+C through the serial console. KeyboardInterrupt normally indicates a user interruption rather than a programming mistake.
Example code import time
while True:
print("Running")
time.sleep(1)Typical error KeyboardInterruptHow to address it Use try and finally to switch off outputs and release initialized hardware when the program stops.
CHAPTER 4 / SUBTOPIC 4.4.5
4.4.5 Complete syntax used by the 18 hardware modules Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition A syntax inventory connects programming constructs to the Python and CircuitPython patterns used in the course hardware files.
Source topic: 13. Complete syntax used by the 18 hardware modules
Learning goal Recognise every Python and CircuitPython syntax pattern that appears in the practical module files.
The examples below form a complete bridge between the programming fundamentals and the hardware source. Select any code line to display its explanation.
Imports and names from libraries
import time
import board
from adafruit_motor import motor
from edu_pico import create_oled, show_module
import module loads a module and uses names such as time.sleep.
from module import name imports selected names directly.
Dotted names such as board.GP14 access attributes inside an imported module.
Literals, variables, constants, and assignment
count = 0
STEP_DELAY = 0.0015
enabled = True
current = "Move hand"
colour = (255, 0, 0)
samples = [0] * 100
count += 1
steps_remaining -= 1
The modules use integers, floating-point numbers, strings, Boolean values, lists, tuples, and dictionaries. Uppercase names identify constants by convention. Augmented assignments such as += update an existing value.
Arithmetic, comparison, Boolean, and membership operators
voltage = raw * 3.3 / 65535
phase = (phase + direction) % 8
direction = -1
ready = magnitude > 0
changed = state != last_state
pressed = not button.value
if gesture in GESTURES:
current = GESTURES[gesture]
Syntax Use in the modules
+ - * /ADC conversion, RMS calculation, timing, and counters
%Wrap the stepper phase and four-digit count
-1Negative throttle and reverse stepper direction
== != < >State, timing, and completion tests
notInvert active-low inputs and toggle outputs
inCheck whether a dictionary contains a gesture code
Decisions and conditional expressions
if data:
key = KEYS.get(data[0], "?" )
elif value > LIMIT:
status = "High"
else :
status = "Normal"
label = "Clockwise" if direction > 0 else "Counter-clockwise"
The last line is a conditional expression: it selects one of two values without opening a multi-line block. Empty byte strings, zero, and None are treated as false in an if condition.
Collections, indexing, slicing, lookup, and unpacking
KEYS = {0xE1: "1" , 0xE2: "2" }
PINS = (board.GP26, board.GP27, board.GP8, board.GP7)
history = (history + key)[-8:]
first_byte = data[0]
key = KEYS.get(first_byte, "?" )
red, green, blue, clear = sensor.color_data
for output, value in zip(outputs, SEQUENCE[phase]):
output.value = value
item[index] selects one item; negative indexes count from the end.
[-8:] is a slice that keeps the final eight characters.
dictionary.get(key, default) safely handles an unknown key.
Tuple unpacking assigns several returned values in one statement.
zip() pairs corresponding items from two collections.
Loops, range, continue, and infinite programs
while True:
now = time.monotonic()
if now < next_step:
time.sleep(0.0005)
continue
for name, colour in COLOURS:
pixels.fill(colour)
for index in range(4):
print(index)
continue skips the remaining statements in the current loop pass. It is used by module 17 while waiting for the next non-blocking step time.
Functions, return values, positional arguments, and keyword arguments
def make_button(pin):
button = digitalio.DigitalInOut(pin)
button.switch_to_input(pull=digitalio.Pull.UP)
return button
button_a = make_button(board.GP0)
uart = busio.UART(tx=board.GP20, rx=board.GP21,
baudrate=9600, timeout=0.01)
pin is a parameter, while board.GP0 is the argument passed to it. Calls can use positional arguments or explicit name=value keyword arguments.
Objects, attributes, properties, and methods
potentiometer = analogio.AnalogIn(board.GP28)
raw = potentiometer.value
pixels.brightness = 0.1
pixels.fill((255, 0, 0))
pixels.deinit()
A constructor such as AnalogIn(...) creates an object.
A property such as .value stores or exposes state.
A method such as .fill(...) asks an object to perform an action.
.deinit() releases pins and peripherals during cleanup.
Hardware constructors used by the modules
i2c = busio.I2C(board.GP5, board.GP4)
spi = busio.SPI(board.GP18, MOSI=board.GP19, MISO=board.GP16)
uart = busio.UART(tx=board.GP20, rx=board.GP21, baudrate=9600)
digital_pin = digitalio.DigitalInOut(board.GP22)
analogue_pin = analogio.AnalogIn(board.GP28)
pwm = pwmio.PWMOut(board.GP6, frequency=50, duty_cycle=0)
microphone = audiobusio.PDMIn(board.GP3, board.GP2,
sample_rate=16000, bit_depth=16)
These constructors cover every communication and pin-access pattern in the 18 practical files: I2C, SPI, UART, digital I/O, analogue input, PWM, and PDM audio input.
Strings, formatting, printing, and hexadecimal values
message = "Voltage: {:.2f} V" .format(voltage)
text = "{:04d}" .format(count)
raw_text = "0x{:02X}" .format(data[0])
print("Key:" , key, "raw:" , raw_text)
Format Meaning
{}Insert a value using its normal representation
{:.2f}Floating-point value with two decimal places
{:04d}Four-digit decimal value padded with zeros
{:02X}Two-digit uppercase hexadecimal value
0xE1Integer literal written in hexadecimal notation
Typed arrays, mathematical functions, and compact expressions
samples = array.array("H" , [0] * 100)
average = sum(samples) / len(samples)
magnitude = math.sqrt(total / len(samples))
relative_db = 20 * math.log(magnitude) / math.log(10) if magnitude else 0
The microphone uses an unsigned-short typed array to store 16-bit samples efficiently. Built-ins such as sum() and len() combine with math.sqrt() and math.log().
Context managers for files
with open("/sd/test.txt" , "w" ) as output_file:
output_file.write("SD Card OK!\n" )
with open("/sd/test.txt" , "r" ) as input_file:
result = input_file.readline().strip()
The with block closes the file automatically, even when an operation inside the block fails.
Exceptions, cleanup, and conditional cleanup
mounted = False
try :
storage.mount(filesystem, "/sd" )
mounted = True
while True:
time.sleep(1)
finally :
if mounted:
storage.umount(filesystem)
spi.deinit()
i2c.deinit()
Every hardware module uses try/finally. Cleanup turns outputs off, unmounts storage when necessary, and releases hardware resources.
Shared helper functions used by every OLED lesson
i2c, oled = create_oled()
show_module(oled, 9, "Potentiometer" , (
"Input: GP28" ,
"Voltage: {:.2f} V" .format(voltage),
"Position: {:.0f}%" .format(percent),
))
The first line uses tuple unpacking to receive two returned objects. The second passes a tuple of display lines across several source lines; the trailing commas separate its items.
Coverage check This section covers every Python syntax family found by parsing the current 18 module files: assignment, attributes, calls, comparisons, dictionaries, lists, tuples, indexing, slicing, arithmetic, modulo, unary operations, decisions, conditional expressions, membership, loops, continue, functions, return values, imports, context managers, and try/finally.
Worked examples: syntax, code and expected output Example 1: imports, formatting and calculation Syntax import module_name
result = expression
text = "FORMAT".format(result)Explanation Import gives access to a module. Arithmetic calculates the value, and format controls how the result is displayed.
Code import math
raw = 32768
voltage = raw * 3.3 / 65535
print("Voltage: {:.2f} V".format(voltage))Expected output or behavior Voltage: 1.65 VExample 2: dictionary lookup and fallback Syntax result = mapping.get(key, default)Explanation The key selects an associated value. get returns the supplied default when the key is not present.
Code keys = {0xE1: "1", 0xE2: "2"}
print(keys.get(0xE2, "?"))
print(keys.get(0xFF, "?"))Expected output or behavior 2
?Example 3: loop, tuple unpacking and zip Syntax for first, second in zip(sequence_1, sequence_2):
statementsExplanation zip pairs corresponding items. The loop unpacks each pair into two variables and stops when the shorter input is exhausted.
Code pins = ("A", "B", "C")
states = (1, 0, 1)
for pin, state in zip(pins, states):
print(pin, state)Expected output or behavior A 1
B 0
C 1CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.5 Integrated mini-project Programming fundamentals RP2040 · CircuitPython · EDU PICO
Learning goal Combine the fundamentals in a complete adjustable LED example.
The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.
Combined mini-project: adjustable LED level CHAPTER 4 / SUBTOPIC 4.5.1
4.5.1 Combined mini-project: adjustable LED level Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition An integrated project combines input, calculation, functions, decisions, repetition, and output control.
Source topic: 14. Combined mini-project: adjustable LED level
Learning goal Combine variables, calculation, a function, a decision, and a loop.
Syntax: common embedded-program structure
import REQUIRED_MODULES
CONSTANTS = VALUES
hardware = CREATE_HARDWARE_OBJECTS
def helper_function(parameters):
PROCESS_DATA_OR_CONTROL_HARDWARE
while True:
input_value = READ_INPUT
result = PROCESS_INPUT
helper_function(result)
time.sleep(INTERVAL)
This project reads the GP28 potentiometer and uses it to control the brightness of five WS2812 LEDs on GP14.
import time
import board
import analogio
import neopixel
potentiometer = analogio.AnalogIn(board.GP28)
pixels = neopixel.NeoPixel(
board.GP14,
5,
brightness=0.1,
auto_write=False,
pixel_order=neopixel.GRB,
)
def show_level(percent):
led_count = int(percent * 5 / 100)
pixels.fill((0, 0, 0))
for index in range(led_count):
if percent >= 80:
pixels[index] = (255, 0, 0)
elif percent >= 40:
pixels[index] = (255, 100, 0)
else :
pixels[index] = (0, 255, 0)
pixels.show()
while True:
adc = potentiometer.value
level = adc * 100 / 65535
show_level(level)
print ("Level: {:.0f}%" .format(level))
time.sleep(0.1)
Extend it Add the OLED and display the ADC value, voltage, and percentage. Then make button A change the LED colour.
Open M08: Potentiometer input
Open M12: WS2812 output CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.6 Interactive concept laboratory Programming fundamentals RP2040 · CircuitPython · EDU PICO
Learning goal Explore the concepts using the source’s calculators and visualisers.
The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.
Interactive concept laboratory CHAPTER 4 / SUBTOPIC 4.6.1
4.6.1 Interactive concept laboratory Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition An interactive concept laboratory changes an input and shows how a program calculation or decision responds.
Source topic: 15. Interactive concept laboratory
The source’s ADC converter, if/elif/else simulator, range visualiser, and list average calculator are retained below as interactive controls.
Learning goal Change input values and immediately observe how the corresponding Python calculation behaves.
CHAPTER 4 / PROGRAMMING FUNDAMENTALS
4.7 Practice and quick reference Programming fundamentals RP2040 · CircuitPython · EDU PICO
Learning goal Apply the concepts independently and check a program systematically.
The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.
Practice tasks and quick reference CHAPTER 4 / SUBTOPIC 4.7.1
4.7.1 Practice tasks and quick reference Programming fundamentals RP2040 · CircuitPython · EDU PICO
Definition Practice tasks apply the syntax patterns to small programming requirements, while a checklist supports code review.
Source topic: 16. Practice tasks and quick reference
Learning goal Apply each concept without copying a complete solution.
Syntax: plan before coding
Variables: Store your name, group number, and a target temperature. Print one formatted sentence.
If–else: Print LOW, MEDIUM, or HIGH for three potentiometer ranges.
For loop: Make each WS2812 LED turn on one at a time.
While loop: Count button presses until the count reaches ten.
Collection: Store five temperature readings in a list and calculate their average.
Function: Write celsius_to_fahrenheit(celsius) and return the answer.
Dictionary: Map keypad values to the names ONE, TWO, and THREE.
Integration: Use a keypad key to select a servo angle.
Program checklist
Are required modules imported?
Are pin names correct?
Are variable and function names meaningful?
Is indentation consistently four spaces?
Does every infinite loop include suitable timing?
Are motors and servos powered safely?
Does cleanup switch outputs off?
CHAPTER 05
Hardware Components YOUR LEARNING GOALS
Chapter 5 learning outcomes By the end of this chapter, students should be able to:
Distinguish microcontrollers from microprocessors and compare RISC/CISC and Harvard/Von Neumann architecture concepts. Explain the roles of the control unit, ALU, registers, and bus interfaces, and trace the fetch–decode–execute cycle. Interpret data, address, and control paths; calculate memory capacity from a stated address organization; and interpret little-endian and big-endian byte sequences. Explain the roles of boot ROM, external flash, and SRAM in an RP2040 system, distinguishing stored firmware and Python files from runtime data. Select GPIO, UART, SPI, or I²C for a stated device connection and interpret a basic interface timing diagram. Calculate timing intervals from stated clock and counting parameters, distinguish software timing from hardware timer/PWM operation, and explain the role of a watchdog. Trace the startup and input–process–output operation of an RP2040/CircuitPython system using a labelled hardware block diagram. Chapter 5 is the RP2040 hardware reference: architecture concepts, real device structure, interfaces, memory and exam-ready timing calculations.
How to use this chapter: learn the general computer concept, map it to the RP2040, then practise with explicit units and stated assumptions. PIC16F877A register examples from the old slides are not RP2040 configuration facts.
10 topics Reference lessons · worked calculations · 6 MCQs per subtopic
Reference sources Use the RP2040 datasheet for silicon facts, the EDU PICO booklet for board wiring/specifications, and CircuitPython documentation for Python API behavior.
CHAPTER 5 / SUBTOPIC 5.1
5.1 Introduction Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Microcontroller A programmable integrated circuit that combines a processor with memory and peripheral interfaces for control tasks. Microprocessor A processor IC that commonly relies on external chips for memory and I/O. System-on-chip (SoC) A chip integrating processor cores, memory interfaces and peripheral blocks. Embedded computing in the RP2040 course An embedded computer combines hardware and software to perform a focused task. It receives information from inputs, processes it in a program, and controls outputs. On the EDU PICO, the RP2040 microcontroller executes CircuitPython code and interfaces with connected devices such as buttons, sensors, displays, LEDs, buzzers and motors.
This chapter develops the hardware concepts behind that process: how the processor, memory, communication paths, clocks and peripheral interfaces work together. Use the RP2040 datasheet for chip specifications and the EDU PICO booklet for board-level connections.
CPU fetch · decode · execute Program & data Flash · SRAM Input & output GPIO · ADC · UART · I²C Clock & reset Conceptual model; RP2040 implements a crossbar and dedicated peripheral blocks. Figure 5.0. Conceptual hardware model for an embedded system. The model introduces the relationships that later sections map to the RP2040. Memory, processor, I/O, clock and control work together; the arrows represent information and control paths, not external wires.Microcontroller and microprocessor comparison Comparison point Microcontroller Microprocessor Typical integration CPU, memory and peripheral blocks integrated in a control-oriented chip. CPU-centered IC commonly paired with external memory and I/O support. Typical use Dedicated sensing, control and embedded applications. General-purpose computing or larger systems. Course example RP2040 on EDU PICO. A processor used in a computer or application processor system. Main design trade-off Compact integrated system and direct peripheral control. More configurable system with external component choices.
RISC and CISC: understand the design idea
Start with the level: RISC and CISC classify the design of a processor’s instruction set. SoC describes the integration of the whole chip. These are related, but they answer different questions.
Definitions
Instruction set architecture (ISA) The set of machine instructions and programmer-visible rules that a processor core can execute. It is the interface between software tools and the CPU.
RISC Reduced Instruction Set Computer: an instruction-set design approach that emphasizes a comparatively small, regular set of operations.
CISC Complex Instruction Set Computer: an instruction-set design approach that includes a richer set of operations, including some instructions that can express more complex tasks.
Load/store design A common RISC approach in which arithmetic and logic instructions work on CPU registers, while separate load and store instructions move values between registers and memory.
An instruction set is the processor’s low-level vocabulary. A program written in Python uses much higher-level instructions such as assignment, addition, and function calls. CircuitPython hides the machine instruction details from students; the runtime and firmware ultimately execute on the RP2040’s processor cores.
Design idea RISC tendency CISC tendency
Instruction set Often a smaller, more regular collection of basic operations. Often a richer collection, including more complex operations.
Work per instruction A task may be expressed as several simple instructions. Some tasks may be expressed with fewer, more elaborate instructions.
Memory operations Commonly uses separate load/store instructions; arithmetic operates on registers. Some architectures allow instructions to operate directly on memory operands.
Design emphasis Regular instruction behavior can simplify decoding and implementation. More complex instructions can require more complex decoding and internal control.
Important caution “Reduced” does not mean weak or incomplete. “Complex” does not mean automatically faster or better.
Illustrative example: one task, different instruction styles Suppose a processor must add two values stored in memory and save the result. A simplified RISC-style sequence might separate memory access from arithmetic:
LOAD R1, [A] # copy value at address A into register R1
LOAD R2, [B] # copy value at address B into register R2
ADD R3, R1, R2 # add the register values
STORE [C], R3 # save the result at address CA CISC-style ISA might provide a richer instruction that combines more of this work into one machine instruction. This is a conceptual illustration only; the exact instructions depend on the specific ISA, and the example is not literal assembly for the RP2040.
Why instruction count alone cannot rank speed: a complex instruction may take multiple clock cycles, while several simple instructions may execute efficiently. A simplified execution estimate is time ≈ instruction count × average cycles per instruction ÷ clock frequency. Actual performance also depends on implementation, memory access, pipeline behavior, compiler/runtime, and the workload.
Where the RP2040 fits
Level What it describes RP2040 course example
Board The complete teaching platform and its connections. EDU PICO connects the RP2040 to flash, power circuitry, and learning devices.
SoC The integrated chip containing processor cores and hardware blocks. RP2040 is an SoC with two Arm Cortex-M0+ cores, SRAM, GPIO, and peripheral controllers.
Processor / ISA The core that executes instructions and the architecture those instructions follow. Cortex-M0+ implements Armv6-M and is a 32-bit RISC processor; it supports the Thumb instruction-set subset.
Course takeaway: the RP2040 is an SoC at the chip-integration level, and its Cortex-M0+ cores use an Arm RISC-based ISA. CISC is included only as a comparison. Neither label describes CircuitPython itself, and neither RISC nor CISC guarantees a performance ranking.
Worked calculation: clock cycles and idealized execution time Given: an idealized operation requires 2,000,000 clock cycles at 125 MHz.
Equation: time = cycles ÷ clock frequency.
Substitution: 2,000,000 ÷
s shaft speed (revolutions/minute, rpm) 125,000,000 = 0.016 s = 16 ms
Interpretation: this is an idealized estimate. CircuitPython runtime work, memory accesses and peripheral waiting can change measured time.
Practice 5.1 — try before revealing the solution A task is modelled as 750,000 cycles at 125 MHz. Estimate the execution time.
State one reason the measured CircuitPython time can be longer.
Worked answer: 750,000 ÷ 125,000,000 = 0.006 s = 6 ms. Runtime, wait states, interrupts, or other work can add time.
The four components form one working system A CPU alone cannot complete a useful embedded task. Memory supplies instructions and stores working data. I/O connects the computer to buttons, sensors and actuators. System buses and interconnect carry the addresses, data and control needed to coordinate those operations. Power, clock and reset support all four components.
Component Question it answers EDU PICO example CPU What operation should happen next? Execute runtime instructions that interpret the program and compare a reading with a threshold. Memory What instructions and values are available? Flash stores firmware and files; SRAM holds live sensor values and display buffers. I/O subsystem How does information enter or leave? GP28 feeds the ADC; GP14 sends NeoPixel data; the I²C controller communicates with sensors and OLED. System interconnect How do the blocks exchange information? Internal address/data/control transactions connect the cores, SRAM and peripheral registers.
At chip level, RP2040 integrates processor cores, SRAM and peripheral controllers. At board level, Pico W adds external flash, a crystal and power circuitry. EDU PICO adds the learning devices and their connections. Therefore “on one chip” does not mean that an entire embedded product needs no external components.
System analysis — a sensor reading is correct but the fan does not turn Trace each component instead of immediately replacing the CPU: check the stored threshold and decision, the output command, the selected GPIO/PWM connection, and the motor driver, motor supply and wiring. A correct display reading proves part of the input path works; it does not prove the actuator power path works.
Calculation tutorial — clock and execution time Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) tCPU ideal CPU execution time (s) Ncycles number of clock cycles Example 1 — Find one clock-cycle period given a frequency of 125 MHz Given: Clock frequency 125,000,000 Hz.
T = 1 ÷ f T = 1 ÷ 125,000,000 Hz T = 8 × 10-9 s T = 8 ns
Interpretation: This is one clock cycle, not necessarily one instruction.
Example 2 — Find ideal execution time for 2,000,000 clock cycles at 125 MHz Given: Cycle count 2,000,000; clock frequency 125 MHz.
tCPU = Ncycles ÷ f tCPU = 2,000,000 ÷ 125,000,000 s tCPU = 0.016 s tCPU = 16 ms
Interpretation: This ideal estimate excludes additional waits and runtime work.
CHAPTER 5 / SUBTOPIC 5.2
5.2 Hardware model Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first CPU The processor block that fetches, decodes and executes instructions. Memory Storage for instructions, program files and data. Bus/interconnect A communication path that transfers data, addresses and control information among blocks. Peripheral A hardware function beyond the CPU core, such as GPIO, ADC, UART, PWM or I²C. Memory-mapped I/O A design approach in which peripheral control/status registers occupy addresses in the processor’s address map. A simple computer diagram names four roles: processor, memory, I/O and the interconnect joining them. Use it to ask three questions about any operation: which value is needed, where is it stored or produced, and which block moves or controls it?
CPU fetch · decode · execute Program & data Flash · SRAM Input & output GPIO · ADC · UART · I²C Clock & reset Conceptual model; RP2040 implements a crossbar and dedicated peripheral blocks. Figure 5.1. Processor, memory and I/O roles. The processor requests instructions/data, acts on them, and communicates with peripherals through the system interconnect. The actual RP2040 fabric is more detailed than the simplified teaching model.Address, data and control: three different jobs Path in the model Question it answers Example Address Which location or peripheral register? Choose a memory byte or a peripheral register. Data What value is transferred? A sensor code, instruction word, or output setting. Control What operation and when? Read, write, enable, interrupt, reset, or timing signals.
RP2040 accuracy note: its internal system uses an AHB-Lite crossbar, bus masters and peripheral buses. “Address/data/control bus” is a conceptual classification; do not draw it as one external bus physically wired across the EDU PICO.
Worked calculation: address capacity from address width Rule: n address bits encode 2ⁿ distinct addresses. If each address selects one byte, capacity = 2ⁿ bytes.
Example: 16 address bits give 2^
addresses = 64 KiB.
Reverse calculation: 8192 bytes = 2¹³, so at least 13 address bits are required.
Practice 5.2 — try before revealing the solution A byte-addressed design needs to address 32 KiB. What is the minimum address width?
A 32-bit-wide path transfers 10 million words per second. Find its ideal data rate in bit/s.
Worked answer: 32 KiB = 32 × 1024 = 32,768 = 2¹⁵ bytes, so 15 address bits. Data rate = 32 × 10,000,000 = 320,000,000 bit/s (320 Mbit/s), before overhead.
Trace a transaction through the hardware model A hardware model describes functional blocks and the information exchanged between them. A programmer’s model describes the registers, instructions and address space visible to low-level software. CircuitPython presents another layer of abstraction: device objects and methods. These views describe the same system at different levels.
Transaction Address path Data path Control meaning Instruction fetch Select the instruction location. Read instruction bits into the processor. Read/fetch; wait for the response when required. Read working data Select the relevant SRAM location. Transfer the stored value to the processor. Read operation. Write working data Select the destination SRAM location. Transfer the new value from the processor. Write operation. Access a peripheral Select a peripheral register in the memory map. Read status/data or write a configuration/output value. Follow the peripheral register’s access rules.
For example, pot.value requests an ADC reading through the CircuitPython driver. The peripheral samples the pin voltage and supplies a conversion result. The runtime creates a Python value in working memory. A comparison then chooses an output action. The Python source line is not itself a machine instruction, and an object name is not a fixed peripheral-register address.
Internal system buses connect chip resources. I²C, SPI and UART are peripheral communication interfaces connecting devices. Both carry information, but they are different layers of the hardware model.
Predict the fault — CPU is running but the input value never changes Check whether the software reads the intended peripheral and pin, whether conversion or communication completes, and whether the signal source and wiring change. A processor executing instructions does not guarantee that a peripheral is configured correctly.
Calculation tutorial — capacity and addresses Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
b number of bits L number of distinct code levels or addressed locations B storage capacity (bytes) w bytes stored per addressed location Afirst first address of the block Alast last inclusive address of the block Example 1 — Find the number of locations and capacity in bytes and KiB for 16 address bits with one byte per location Given: Byte-addressed memory; 16 address bits.
L = 2b L = 216 L = 65,536 B = L × w B = 65,536 × 1 byte B = 65,536 bytes B = 64 KiB
Interpretation: One KiB is 1024 bytes; state the bytes per location before calculating.
Example 2 — Find the last inclusive byte address of an 8 KiB block starting at 0x2000 Given: First byte address 0x2000; length 8192 byte locations.
Alast = Afirst + L − 1 Alast = 0x2000 + 0x2000 − 1 Alast = 0x3FFF
Interpretation: Subtract one because the first address is included in the block.
CHAPTER 5 / SUBTOPIC 5.2.1
5.2.1 Central processing unit Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Control unit Processor logic that coordinates instruction steps and control signals. Arithmetic logic unit (ALU) Processor logic that performs arithmetic and Boolean operations. Register A small, fast storage location inside the CPU. Program counter (PC) A register that identifies the instruction address used next, subject to branches and exceptions. Fetch–decode–execute A useful model of obtaining an instruction, interpreting it and carrying out its operation. The RP2040 contains two Arm Cortex-M0+ processor cores. Each is a 32-bit RISC processor. One core is sufficient for the course’s normal CircuitPython examples; dual-core hardware is a chip capability, not a requirement to run two CircuitPython programs in the course.
1 · Fetchobtain instruction → 2 · Decodeidentify operation → 3 · Executeoperate on data ↻
Registers hold temporary values used during execution. The ALU performs operations such as addition and comparison. The control unit coordinates the steps. Real processors pipeline and overlap internal work; the three-stage model is a learning aid, not a complete microarchitecture specification.
Worked calculation: clock period and estimated CPU time Clock period:
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) T = 1/f
. At 125 MHz,
T period of one cycle (s unless another time unit is stated) s shaft speed (revolutions/minute, rpm) T = 1/125,000,000 s = 8 ns
per clock cycle.
Idealized task: 2 million cycles × 8 ns/cycle = 16,000,000
Important: do not treat “32-bit” as “32 cycles” or assume each Python statement takes one clock.
Practice 5.2.1 — try before revealing the solution Calculate the ideal clock period at 100 MHz.
An operation requires 3 million cycles at 100 MHz. Estimate its ideal time.
Worked answer: T = 1/100,000,000 = 10 ns. Time = 3,000,000/100,000,000 = 0.03 s = 30 ms.
Control unit, ALU, interface logic and registers RP2040 · Cortex-M0+
Explore both processor cores RP2040 has two Cortex-M0+ processor cores: Core 0 and Core 1. Both are shown with equal detail below. Select a core to highlight it, or compare both; selecting a block highlights its equivalent in each core.
Both cores Core 0 Core 1
Control logic Fetch and decode Core registers Operands and state ALU Arithmetic and logic NVIC Interrupts and exceptions AHB-Lite Core memory interface Shared resources Crossbar, memory and I/O
Tour next block Reset explorer
Each core has its own registers, ALU, control logic and NVIC. Both access shared SRAM and system resources. This simplified view shows the main AHB-Lite route; SIO, DMA, ROM, clocks and debug are omitted. Highlighting a core changes only the diagram.
Figure 5.2. RP2040 dual-core architecture: Core 0 and Core 1 side by side, with separate processor state and shared system resources. Internal core connections are conceptual teaching paths. Original source diagram (slide 17) Dual-core clarification “Dual-core” means two processor cores inside one RP2040 chip. The cores can execute independently, each with its own register state, but share memory and many peripherals. Two cores do not double the SRAM capacity or automatically run a Python script twice. The course’s normal CircuitPython examples do not require students to start a separate program on Core 1.
The control unit decodes an instruction and coordinates the required actions: choose source registers, select an ALU operation, request a memory access, and select where the result is stored. The ALU operates on binary values. Bus-interface logic coordinates transfers between processor execution logic and the system interconnect. Registers hold the small set of values needed immediately by the processor.
Cortex-M0+ · ALU Follow a 32-bit addition Choose an example card, then tap a stage or step through the data path. ADDS reads R0 and R1, writes the result to R2 and updates APSR flags.
Normal addition 7 + 3 Unsigned carry FFFFFFFF + 1 Signed overflow 7FFFFFFF + 1
1 · Read operands R0 + R1 0x000000070x000000032 · Compute 32-bit ALU ADDS R2, R0, R13 · Write result R2 0x0000000A4 · Update flags APSR N=0 Z=0 C=0 V=0
N · Negative 0
Z · Zero 0
C · Unsigned carry 0
V · Signed overflow 0
Start addition trace Next trace step Reset explorer
Try your own operands in the 32-bit addition model below
Figure 5.3. Cortex-M0+ register-to-ALU data path, shown with flag-setting addition. The values are simulated examples, not live RP2040 registers. Original source diagram (slide 25) Fetch, decode and execute: trace the role of each block Stage What changes Student interpretation Fetch The processor uses its instruction address to obtain instruction bits. The program counter identifies the instruction stream. Instruction bits are distinct from sensor data. Decode Control logic identifies the operation and operands. The CPU determines whether to add, compare, load, store or branch. Execute Registers, memory, condition flags or the instruction path change. A branch can redirect the program counter; execution is not always a straight line.
The Cortex-M0+ has a two-stage pipeline. Fetch–decode–execute remains a useful conceptual sequence, but stages can overlap and instructions do not all take the same number of cycles. Reset starts through the boot process, not directly at a Python main function. Calls and exceptions also affect the instruction path and stack.
Registers: distinguish data, addresses and processor state Cortex-M0+ · RP2040 Explore the processor registers Tap a register card to see its role, example and connection to the processor. Each RP2040 core has its own register state.
Data and addresses · R0–R12 R0 Working register R1 Working register R2 Working register R3 Working register R4 Working register R5 Working register R6 Working register R7 Working register R8 Working register R9 Working register R10 Working register R11 Working register R12 Working register
Stack and instruction flow SP / R13 Stack pointer LR / R14 Return information PC / R15 Instruction address
Status and control xPSR Flags + processor state PRIMASK Exception mask CONTROL Privilege + stack selection
Follow one addition ADDS R2, R0, R1 adds 7 and 3. Step through the source registers, destination and condition flags.
R0 · 7 R1 · 3
→ ALU → R2 · 10 APSR · N/Z/C/V
Start addition trace Next trace step Reset explorer
Figure 5.4. Cortex-M0+ register organization for each RP2040 core. xPSR combines application flags, exception identity and execution state; PRIMASK and CONTROL are separate special registers. Original source diagram (slide 32) Reference: RP2040 datasheet, Section 2.4 (Cortex-M0+) · Arm Cortex-M0+ Devices Generic User Guide
Register or concept Function RP2040 interpretation R0–R12 General-purpose working registers for values and addresses. Each Cortex-M0+ core has its own processor register state. SP / R13 Points to a stack location; it does not hold the entire stack. The stack itself occupies memory and supports calls and exception handling. LR / R14 Holds return-link information for calls and exception return. Function return is more than simply incrementing the program counter. PC / R15 Tracks the instruction address used by execution. Branches change the instruction path. PSR / APSR Records processor status; APSR includes N, Z, C and V condition flags. Interrupt masking is controlled separately; do not reuse another chip’s status-bit layout. Instruction register, conceptual Holds or represents the instruction being decoded in a teaching model. It is not a separate Python-accessible general-purpose register.
Binary arithmetic: carry and signed overflow are different An unsigned 32-bit value ranges from 0 to 4,294,967,295. A signed two’s-complement 32-bit value ranges from −2,147,483,648 to 2,147,483,647. The same 32 bits can be interpreted either way. For a flag-setting addition, C describes carry out of bit 31, V describes a signed result outside the signed range, Z indicates a zero result, and N reflects result bit 31. Not every instruction updates every flag.
Addition 32-bit result Flags for this addition 0xFFFFFFFF + 0x00000001 0x00000000 N=0, Z=1, C=1, V=0 0x7FFFFFFF + 0x00000001 0x80000000 N=1, Z=0, C=0, V=1 0x0000004A + 0x00000079 0x000000C3 N=0, Z=0, C=0, V=0; bit 31 is zero.
A 32-bit core does not force CircuitPython variables to be 32-bit machine registers. Python values are managed runtime objects. The following model explains fixed-width hardware addition; it does not read the real CPU flags.
Interactive 32-bit addition and condition flags Calculation tutorial — clock and execution time Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) tCPU ideal CPU execution time (s) Ncycles number of clock cycles Example 1 — Find one clock-cycle period given a frequency of 125 MHz Given: Clock frequency 125,000,000 Hz.
T = 1 ÷ f T = 1 ÷ 125,000,000 Hz T = 8 × 10-9 s T = 8 ns
Interpretation: This is one clock cycle, not necessarily one instruction.
Example 2 — Find ideal execution time for 2,000,000 clock cycles at 125 MHz Given: Cycle count 2,000,000; clock frequency 125 MHz.
tCPU = Ncycles ÷ f tCPU = 2,000,000 ÷ 125,000,000 s tCPU = 0.016 s tCPU = 16 ms
Interpretation: This ideal estimate excludes additional waits and runtime work.
CHAPTER 5 / SUBTOPIC 5.2.2
5.2.2 System buses Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Address path Selects the memory location or peripheral register being accessed. Data path Carries instruction or data values between blocks. Control path Carries signals that coordinate a transfer or operation. Crossbar A switching fabric that can route several bus masters to several destinations, subject to arbitration. Transfer width The number of bits moved in one transfer. A traditional block diagram often draws one shared system bus. RP2040 uses a more capable internal fabric: multiple bus masters, including processor cores and DMA, access memory and peripherals through crossbar/interconnect logic. The concepts of address, data and control still help students reason about a transfer.
Calculation Equation Worked result Address capacity 2ⁿ addresses 16-bit byte addressing → 2¹⁶ = 65,536 bytes = 64 KiB. Bits to bytes bits ÷ 8 32-bit word → 4 bytes. Ideal data rate bits per transfer × transfers/s 32 bits × 10 Mtransfers/s = 320 Mbit/s.
Units matter: b is bit, B is byte; 1 byte = 8 bits. “Mbit/s” is not “MB/s.” Divide bit/s by 8 to obtain the ideal byte/s rate before protocol overhead.
Worked calculation: required address bits Question: how many address bits are needed to address 64 KiB byte-by-byte?
64
bytes storage unit, eight bits KiB = 64 × 1024 = 65,536 bytes = 216
Answer: 16 address bits.
Practice 5.2.2 — try before revealing the solution A byte-addressed memory holds 128 KiB. Find its minimum address width.
Convert an ideal 320 Mbit/s transfer rate to MB/s, using decimal units.
Worked answer: 128 KiB = 131,072 bytes = 2¹⁷, so 17 address bits. 320 Mbit/s ÷ 8 = 40 MB/s, before overhead.
Bus-interface logic links the CPU to the system RP2040 · Bus fabric Trace a request through RP2040 The original picture was a general CPU bus-interface model. RP2040 implements those address, data and control roles using the architecture shown here. Select a source, destination and operation, then step through a conceptual transfer.
1 · Choose the requester Core 0 Cortex-M0+ bus master Core 1 Cortex-M0+ bus master DMA read port Reads source data DMA write port Writes destination data
2 · Choose the destination ROM One crossbar port Flash XIP One crossbar port SRAM banks Six crossbar ports Fast peripherals One shared port APB bridge One crossbar port SIO Separate core IOPORT path
Read Write
Data direction:
Illustrative payload: —
Start transfer Next transfer step Reset explorer
Figure 5.5. RP2040 bus-interface teaching model: four AHB-Lite master ports, a 4:10 crossbar and grouped downstream destinations. SIO uses each core’s separate IOPORT. This shows architectural roles, not exact signal waveforms. Original source diagram (slide 28) · RP2040 reference: Sections 2.1 and 2.3 How this relates to the CPU diagrams Figures 5.2–5.4 use the Cortex-M0+ cores actually present in RP2040, with simplified control/ALU/register paths. Figure 5.5 shows how their bus interfaces reach the wider chip. A CPU core, its bus interface and the shared interconnect are different parts of the same system. Address/data/control are general functions; the AHB-Lite crossbar and separate SIO path are the RP2040 implementation.
Read and write are described from the CPU’s perspective. During a read, the selected memory or peripheral supplies data to the CPU. During a write, the CPU supplies data to the selected destination. The address selects the destination, while control information determines the operation and when it completes. A real on-chip fabric can have separate channels rather than one shared set of external wires.
Data width, address width and memory capacity Address width answers how many locations can be identified. Data width answers how many bits a particular transfer can carry. Storage capacity also depends on how many bytes each addressed location represents. State whether the example is byte-addressed or word-addressed before using an equation.
b number of bits L number of distinct code levels or addressed locations B storage capacity (bytes) w bytes stored per addressed location L = 2b B = L × w
Alast last inclusive address of the block Afirst first address of the block L number of distinct code levels or addressed locations Alast = Afirst + L − 1
Given organization Calculation Result 12 address bits, one byte per location 2^12 = 4096 locations 4 KiB; addresses 0x000–0xFFF 22 address bits, one byte per location 2^22 = 4,194,304 locations 4 MiB; addresses 0x000000–0x3FFFFF 13 address bits, two bytes per location 8192 × 2 = 16,384 bytes 8 Kiwords of 16-bit words = 16 KiB 32 KiB, byte-addressed 32 × 1024 = 2^15 bytes 15 offset bits identify each byte within the block.
Worked address-range examples An 8 KiB byte-addressed block starts at 0x2000. Its length is 8192 = 0x2000 bytes, so the last address is 0x2000 + 0x2000 − 1 = 0x3FFF. A 16 KiB block starting at 0xC000 ends at 0xFFFF. The final “−1” matters because the starting location is included.
Address decoding selects which block responds to an address range. Offset bits choose a location inside that block. For an 8 KiB block, 13 offset bits are sufficient, but the complete CPU address can be much wider. Do not interpret this exercise as 13 external address wires that must be connected to the EDU PICO.
Address-range practice — include units and addressing assumptions A 4 KiB byte-addressed block starts at 0x8000. Last address = 0x8000 + 0x1000 − 1 = 0x8FFF; 12 offset bits select its bytes. A device with 10 address inputs and 16-bit locations stores 1024 × 2 = 2048 bytes = 2 KiB.
Calculation tutorial — capacity and addresses Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
b number of bits L number of distinct code levels or addressed locations B storage capacity (bytes) w bytes stored per addressed location Afirst first address of the block Alast last inclusive address of the block Example 1 — Find the number of locations and capacity in bytes and KiB for 16 address bits with one byte per location Given: Byte-addressed memory; 16 address bits.
L = 2b L = 216 L = 65,536 B = L × w B = 65,536 × 1 byte B = 65,536 bytes B = 64 KiB
Interpretation: One KiB is 1024 bytes; state the bytes per location before calculating.
Example 2 — Find the last inclusive byte address of an 8 KiB block starting at 0x2000 Given: First byte address 0x2000; length 8192 byte locations.
Alast = Afirst + L − 1 Alast = 0x2000 + 0x2000 − 1 Alast = 0x3FFF
Interpretation: Subtract one because the first address is included in the block.
CHAPTER 5 / SUBTOPIC 5.2.3
5.2.3 Memory organization Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Boot ROM Read-only on-chip memory containing startup and boot support code. SRAM Volatile, fast working memory used for runtime code/data, stacks and buffers. QSPI flash External non-volatile storage connected over a quad-SPI interface. XIP Execute in place: RP2040 maps external flash reads into the system address space so code can run from flash. Endianness The byte order used to store multi-byte values in memory. The RP2040 has 264 KiB of on-chip SRAM and a boot ROM; the board adds external flash whose capacity depends on the board design. The EDU PICO booklet identifies the course board as a Pico W with 2 MB flash. The RP2040 itself does not specify the external flash capacity; that is selected by the board designer. SRAM is working space; flash retains files and firmware when power is removed.
Memory resource Volatile? Role in the course system Boot ROM No Startup and boot support. External QSPI flash No CircuitPython firmware and files such as code.py and libraries. 264 KiB SRAM Yes Runtime variables, stack, buffers and active program data. XIP cache Temporary/cache Speeds access to recently read flash data.
Memory-capacity calculations Worked calculation: capacity, address bits and endianness 264 KiB SRAM = 264 ×
To address 270,336 bytes individually, choose n where 2^n ≥ 270,336. Since 2^
is too small and 2^
is sufficient, at least 19 address bits are needed for this capacity.
For a 32-bit value 0x12345678, little-endian byte order is 78 56 34 12 ; big-endian order is 12 34 56 78 .
Architecture note: Harvard and Von Neumann are useful ways to compare instruction/data organization. For RP2040, students should explain its actual mapped memory and XIP arrangement rather than assume PIC-specific Harvard diagrams apply unchanged.
Practice 5.2.3 — try before revealing the solution Convert 2 MiB to bytes (1 MiB = 1024 × 1024 bytes).
How many bits are needed to address 2 MiB byte-by-byte?
Write 0xA1B2C3D4 in little-endian byte order.
Worked answer: 2 MiB = 2,097,152 bytes = 2²¹, so 21 address bits. Little-endian order: D4 C3 B2 A1.
Memory cells, locations and access operations RP2040 · Memory access Select an address, then read or write RP2040 uses a byte-addressed memory map. This explorer shows aligned 32-bit accesses through a core’s AHB-Lite interface and the crossbar. Choose a region card and one of four word addresses.
Core 0 Core 1
Boot ROM 0x00000000External flash via XIP 0x10000000SRAM4 example 0x20040000
Word address · tap to select +0 +1 +2 +3 32-bit word
Each byte column is an offset from the row’s address. Little-endian order stores the least significant byte at offset +0. A 32-bit word occupies four consecutive byte addresses.
Read selected word Write selected word Reset explorer
Figure 5.6. RP2040 mapped-memory access: address and control select a region and location; read data returns to the core, while write data travels to writable SRAM. Byte order and word addresses are shown explicitly. Original source diagram (slide 52) · RP2040 reference: Sections 2.2 and 2.6 A memory cell stores information; an addressable location groups bits into the unit selected by an address. In a byte-addressed model, each address identifies eight bits. A read retrieves the selected information; a write replaces it subject to the memory technology’s rules. Do not assume every memory technology is built from flip-flops or that all reads and writes have the same timing.
Memory technologies: permanence and write behaviour Type Power-off retention How it is used or changed Mask ROM Non-volatile Contents are established during manufacture. OTP ROM Non-volatile One-time programmable storage. EPROM Non-volatile Traditional erasable devices use ultraviolet erasure and reprogramming. EEPROM Non-volatile Electrically erasable/programmed; write timing and endurance depend on the device. Flash Non-volatile Typically erase in blocks before programming; used for board firmware and files. FRAM Non-volatile Uses ferroelectric storage; characteristics depend on the selected chip. SRAM Volatile Fast working storage that needs power but no DRAM-style refresh; RP2040 uses SRAM. DRAM Volatile Requires periodic refresh; commonly used in larger computer systems.
The table compares technologies; it does not mean all of them are fitted to EDU PICO. The course hardware uses boot ROM, on-chip SRAM and board-level QSPI flash. Available file space and Python heap are smaller than total physical flash and SRAM capacities.
Memory banks and word size RP2040 · SRAM Which SRAM bank holds this word? RP2040 has four 64 KiB SRAM banks and two 4 KiB banks. In the first 256 KiB address region, consecutive 32-bit words cycle through banks 0, 1, 2 and 3. Each bank holds complete words, not just a low or high byte.
Striped region · tap a word address
SRAM0 · 64 KiB 0x200000000x200000100x200000200x20000030
SRAM1 · 64 KiB 0x200000040x200000140x200000240x20000034
SRAM2 · 64 KiB 0x200000080x200000180x200000280x20000038
SRAM3 · 64 KiB 0x2000000C0x2000001C0x2000002C0x2000003C
Selected bank: SRAM0
Word index inside that bank: 0
Next consecutive word Reset explorer
Figure 5.7. RP2040 SRAM banking and word striping. The displayed addresses are real mapped addresses; highlighting is a teaching simulation. Original general memory-bank picture (slide 58) · RP2040 reference: Section 2.6.2, Table 153 General comparison only: two 8-bit banks could form a 16-bit data path; two banks of 2 KiB would give 4 KiB total. This is a different arrangement from RP2040’s word-striped SRAM. Bank selection describes where a word resides; endianness describes byte order within that word.
Endianness changes byte order, not the value’s bit width RP2040 · Little-endian Same word, different byte order A 32-bit word contains four bytes. Matching colours identify the same byte in the word and in memory. Tap a byte or memory cell to follow it. RP2040 uses the little-endian row; big-endian is shown for comparison only.
0x12345678 0xA1B2C3D4 Reset explorer
Word bytes · most significant on the left 31–24 23–16 15–8 7–0
Most significant byte Least significant byte
Little-endian · RP2040 0x200400000x200400010x200400020x20040003
Lowest address Increasing addresses →
Big-endian · comparison 0x200400000x200400010x200400020x20040003
Lowest address Increasing addresses →
Selected byte: · Bits:
Correctly reconstructed word (either order):
Show a wrong byte-order interpretation Little-endian bytes decoded incorrectly as big-endian:
Figure 5.8. Interactive byte-order comparison for a 32-bit word. RP2040 stores the least significant byte at the lowest address. Original source diagram (slide 63) · RP2040 reference: Section 2.4.1.2 Fixed worked example below: 0x12345678 at 0x20040000. Changing the interactive word above does not change this reference table.
Address Little-endian: 0x12345678 Big-endian: 0x12345678 0x20040000 0x78 0x12 0x20040001 0x56 0x34 0x20040002 0x34 0x56 0x20040003 0x12 0x78
RP2040 uses little-endian representation. Endianness becomes important when assembling multi-byte sensor data, file records or communication packets. A protocol may specify a byte order independently of the processor. “Least significant byte first in memory” does not by itself specify whether a serial link sends the least significant bit first.
Von Neumann and Harvard: separate the architectural ideas RP2040 · Code and data Compare the models, then trace RP2040 Von Neumann and Harvard describe architectural ideas. Use the RP2040 view to see the implemented memory paths instead of assuming that separate flash and SRAM mean separate CPU instruction and data buses.
Classic Von Neumann Classic Harvard RP2040 paths
Fetch instruction · flash 0x10001000Fetch instruction · SRAM 0x20040000Read data · SRAM 0x20040004Read data · flash 0x10002000
Core 0 Core 1 Cache hit Cache miss
Start trace Next trace step Reset explorer
Selected address: 0x10001000
Figure 5.9. Classic memory-architecture models compared with RP2040’s unified mapped-memory access, crossbar, SRAM and cached flash XIP paths. Original source diagram (slide 67) · RP2040 reference: Sections 2.3 and 2.6.3 In the traditional Von Neumann model, instructions and data share a memory organization and access path. In the traditional Harvard model, instruction and data memories and paths are separate. Real devices can combine features. RP2040’s Cortex-M0+ cores use a unified system address space and an AHB-Lite interface to the bus fabric; SRAM can contain both code and data, and external flash is mapped through XIP. Explain these actual paths instead of classifying the entire chip from the location of one memory block.
Calculation tutorial — capacity and addresses Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
b number of bits L number of distinct code levels or addressed locations B storage capacity (bytes) w bytes stored per addressed location Afirst first address of the block Alast last inclusive address of the block Example 1 — Find the number of locations and capacity in bytes and KiB for 16 address bits with one byte per location Given: Byte-addressed memory; 16 address bits.
L = 2b L = 216 L = 65,536 B = L × w B = 65,536 × 1 byte B = 65,536 bytes B = 64 KiB
Interpretation: One KiB is 1024 bytes; state the bytes per location before calculating.
Example 2 — Find the last inclusive byte address of an 8 KiB block starting at 0x2000 Given: First byte address 0x2000; length 8192 byte locations.
Alast = Afirst + L − 1 Alast = 0x2000 + 0x2000 − 1 Alast = 0x3FFF
Interpretation: Subtract one because the first address is included in the block.
CHAPTER 5 / SUBTOPIC 5.2.4
5.2.4 I/O subsystem Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first GPIO A configurable general-purpose digital input/output pin. ADC An analogue-to-digital converter that represents an input voltage as a number. UART An asynchronous serial interface that frames data with start/stop bits. I²C A synchronous two-wire addressed serial bus using SCL and SDA. SPI A synchronous serial interface commonly using SCLK, MOSI, MISO and chip select. The I/O subsystem connects software decisions to physical signals. GPIO handles digital levels. ADC samples voltage. UART, I²C and SPI exchange serial data according to different timing and wiring rules. Select an interface based on the device protocol; a device’s datasheet is authoritative for its timing and voltage requirements.
Interface Timing calculation students can perform Example GPIO / ADC ADC code-to-voltage and threshold comparison. A changing potentiometer voltage. UART Frame bits ÷ baud = approximate frame time. 8-N-1 sends 10 bits per data byte. I²C Clock count × SCL period; include address/data ACK bits. Two bytes need at least 18 SCL pulses. SPI Bits ÷ (clock × data lines) for ideal transfer time. 8 bits at 1 MHz on one data line = 8 μs.
Worked calculation: serial transfer-time estimates UART 8-N-1: 1 start + 8 data + 1 stop = 10 transmitted bits per byte. At 9600 bit/s, one frame takes 10/9600
s shaft speed (revolutions/minute, rpm) s = 1.0417 ms
; ideal throughput is 960 bytes/s before application/protocol gaps.
I²C: each 8-bit byte is followed by a ninth clock for ACK/NACK. Two transmitted bytes therefore need at least 18 clocks. At 400 kHz, 18/400,000 s = 45 μs , excluding START/STOP and bus timing.
SPI: 8 bits at 1 MHz takes 8/1,000,000 s = 8 μs , excluding chip-select and command overhead.
These are lower-bound estimates. Include address bytes, acknowledgements, command bytes, sensor conversion time and software overhead when estimating a complete transaction.
Practice 5.2.4 — try before revealing the solution At 115,200 baud, estimate the duration of one UART 8-N-1 byte.
A 6-byte I²C payload is sent, ignoring address bytes. Find the minimum payload-plus-ACK clocks and time at 100 kHz.
Worked answer: UART: 10/115,200 s ≈ 86.8 μs. I²C: 6 × 9 = 54 clocks; 54/100,000 = 540 μs, excluding address and START/STOP.
Anatomy of an I/O interface An I/O interface commonly contains control registers, status information, data registers or buffers, and logic that translates internal transactions into external signals. Software configures the interface, checks or waits for a state, and transfers data. The external device may also need a conversion delay, handshake or driver circuit.
Interface part Role Example Control/configuration Choose operating mode and timing. UART baud rate; ADC channel; GPIO direction. Status Report readiness or completion. Received data available; conversion complete. Data register / FIFO Hold values waiting to be transferred or consumed. UART transmit/receive buffers. External signal logic Produce or sample electrical signals according to a protocol. SPI clock and data edges; GPIO input sensing.
Follow one byte from the sender’s buffer to the receiver’s buffer, then read it in software. This is a slowed teaching model of UART 8-N-1: one start bit, eight data bits sent least significant bit first, no parity and one stop bit.
DirectionEDU PICO → peer Peer → EDU PICO Byte (hex: 00–FF) Baud rate at both ends9600 19200 115200
EDU PICO UART UART peer CPU / CircuitPython Peer application TX buffer — RX buffer — TX buffer — RX buffer — TX RX TX RX Common GND GP20 TX / GP21 RX 3.3 V logic 1. Queue byte 2. Next bit Complete frame 3. Read RX buffer Reset simulation
Application console —
Figure 5.10. Interactive UART buffering and serial transfer. The diagram models one byte at a time; real UART hardware/software buffers can hold more. The displayed waveform timing follows the selected baud rate, while button stepping is deliberately slow. Original source diagram (slide 77) Initialize UART serial communication in CircuitPython This example configures EDU PICO’s UART connection for a compatible 3.3 V UART peer using 9600 baud and 8-N-1. Connect GP20 TX to peer RX, GP21 RX to peer TX, and GND to peer GND. Both endpoints must use matching baud rate, data bits, parity and stop bits. GP21 is also used by the EDU PICO buzzer path, so release that pin from buzzer control before creating the UART.
import time
import board
import busio
# EDU PICO UART pins: cross TX to peer RX and RX to peer TX.
with busio.UART(
tx=board.GP20,
rx=board.GP21,
baudrate=9600,
bits=8,
parity=None,
stop=1,
timeout=0.01,
receiver_buffer_size=64,
) as uart:
written = uart.write(b"A") # ASCII A = 0x41
print("TX bytes written:", written)
while True:
if uart.in_waiting > 0:
data = uart.read(1)
if data is not None:
print("RX byte: 0x{:02X}".format(data[0]))
time.sleep(0.001)Setting or statement Role and effect import board / busio board supplies pin names; busio supplies the hardware UART class. tx=board.GP20 / rx=board.GP21 Select transmit and receive pins from the EDU PICO UART wiring used in the course. baudrate=9600 Request 9600 transmitted bit intervals per second; this is not 9600 data bytes per second. bits=8, parity=None, stop=1 Eight data bits, no parity bit, one stop bit. Start/stop framing makes ten bit intervals per byte. timeout=0.01 Read timeout in seconds: up to about 10 ms when the requested data is not available. receiver_buffer_size=64 Request a 64-byte receive buffer; unread bytes can accumulate until software consumes them. uart.write(b"A") Send a bytes object containing ASCII 0x41. The API reports the number of bytes written; wire-level framing is handled by UART. uart.in_waiting Number of unread bytes currently available in the receive buffer. uart.read(1) Read up to one byte. It returns a bytes object, or None when the read times out with no data. data[0] Extract the byte as an integer from 0 to 255; format it as two hexadecimal digits. with busio.UART(...) as uart Create the UART and release its resources when the managed block exits.
The UART link is separate from the USB serial console used by Thonny: print displays diagnostics on USB, while uart.write transmits through GP20. A transmitted 0x41 means “A” only under an ASCII interpretation. For M11’s capacitive keypad, use its documented 0xE1–0xEC key codes and protocol instead of assuming it echoes this generic byte.
Reference: CircuitPython busio.UART initialization and read/write API
Parallel and serial transfer Figure 5.11. Parallel transfer places several data bits on separate paths; serial transfer sends a sequence of bits over fewer data paths. Source picture: supplied Chapter 5 Word document, slide 73. Parallel and serial describe how bits are carried, not a guaranteed speed ranking. Throughput depends on clock rate, lane count, framing, electrical constraints and overhead. UART is asynchronous: transmitter and receiver agree on baud/framing but do not share a clock wire. SPI and I²C are synchronous: a clock signal coordinates data transfer. Power and ground are not data lanes.
CPU and peripheral interaction: polling and interrupts Polling repeatedly checks a status or input. An interrupt requests processor attention when an event occurs. The processor then runs an interrupt handler under hardware/software rules. Interrupts do not make a sensor conversion instantaneous. In ordinary course CircuitPython code, drivers and runtime support handle much of this detail; reading a property or calling a method is the student-facing operation.
For an AHT20 measurement, I²C communication triggers or reads the sensor, but the sensor performs the temperature/humidity conversion internally. Wire transfer time and conversion time are separate. For the onboard potentiometer, the RP2040 ADC performs the voltage conversion. These are two different acquisition paths even though both ultimately produce Python numbers.
Read a timing diagram from left to right Move the time cursor to inspect the single signal and multi-bit bus separately. A valid bus band represents a stable word, not a third voltage level.
Time cursor
Single-signal state:
Bus state:
Next interval Reset explorer
Figure 5.12. Interactive timing notation: HIGH/LOW, high impedance, valid words and changing or invalid bus values. Dashed mid-height lines denote high impedance; they do not specify a voltage. Original source diagram (slide 78) Choose a read or write cycle, then scrub or step through time. Change the read access delay to see when data becomes valid and whether it meets the sampling requirement.
OperationRead Write Read access delay (ns)30 Time cursor (ns)0
Data direction:
Data becomes valid (ns):
Available setup / hold (ns):
Next event Reset explorer
Model assumptions: address valid from 10–95 ns; active-LOW enable from 20–90 ns; sample at 70 ns; minimum data setup and hold are both 10 ns. Read data is driven by memory after the selected access delay. Write data is driven by the CPU from 10–90 ns. The coloured windows show the required 10 ns before and after sampling. These chosen values illustrate timing; they are not RP2040 specifications or direct CircuitPython GPIO timings.
Figure 5.13. Interactive conceptual read/write timing with active-LOW enable, address validity, data direction, access delay and setup/hold checks. R/W is HIGH for read and LOW for write in this model; actual devices define their own signals and sampling events. Original source diagram (slide 79) First identify the selected operation, active signal levels and the relevant sampling edge. Then track address validity, data direction and the time for data to settle. A bus band labelled “valid” represents a stable multi-bit value; it is not a third digital logic level. High impedance means an output is not actively driving the line; it does not mean the line is necessarily at 0 V.
Timing term Meaning Setup time Minimum time data must already be stable before the sampling event. Hold time Minimum time data must remain stable after the sampling event. Access / propagation time Delay from a request or input change until the corresponding output becomes valid. Chip select / enable Identifies when the target participates; active polarity must be read from the device specification.
Timing practice — check the sampling edge Data becomes stable 30 ns before an edge and remains stable for 15 ns afterwards. A device requires 20 ns setup and 10 ns hold: both requirements are met, with margins of 10 ns and 5 ns. If data settles only 12 ns before the edge, setup is violated by 8 ns even when the hold requirement is met.
Calculation tutorial — serial transfer time Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Nbits transmitted bits per frame or transfer Nbytes number of transmitted bytes fbus bus clock or serial bit rate (Hz or bit/s as stated) tframe frame or transfer time (s) Example 1 — Find the transmission time of one 8N1 UART frame at 115,200 bit/s Given: 8N1 framing; 10 transmitted bits per byte.
tframe = Nbits ÷ fbus tframe = 10 ÷ 115,200 s tframe ≈ 86.806 µs
Interpretation: This excludes gaps between frames.
Example 2 — Find the clocked transfer time for six I²C data bytes at 100 kHz, including ACK/NACK but excluding the address Given: Six data bytes; nine clocks per byte including ACK/NACK.
Nbits = Nbytes × 9 Nbits = 6 × 9 Nbits = 54 tframe = Nbits ÷ fbus tframe = 54 ÷ 100,000 s tframe = 540 µs
Interpretation: This counts data clocks only; address, START/STOP and software add time.
Example 3 — Find the transfer time of one eight-bit SPI byte at a 1 MHz clock, excluding overhead Given: Eight bits; bus clock 1,000,000 Hz.
tframe = Nbits ÷ fbus tframe = 8 ÷ 1,000,000 s tframe = 8 µs
Interpretation: This excludes chip-select and command overhead.
CHAPTER 5 / SUBTOPIC 5.3
5.3 RP2040 hardware structure Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first System-on-chip (SoC) A single IC containing processor cores and major system/peripheral blocks. Clock domain A set of logic operating from a particular clock source/rate. Peripheral A hardware block serving a function such as PWM, ADC, UART, I²C, SPI or timer. DMA Direct Memory Access: a hardware mechanism that moves data between memory/peripherals with reduced CPU involvement. PIO Programmable I/O state machines for implementing precise custom digital protocols. The RP2040 combines two Arm Cortex-M0+ cores, on-chip SRAM, external flash interface, GPIO and dedicated peripheral controllers. DMA and PIO extend its ability to move data and generate/receive timed signals. The clock system supplies different blocks; 125 MHz is the commonly used nominal clk_sys configuration, not an immutable property under every configuration.
CPU fetch · decode · execute Program & data Flash · SRAM Input & output GPIO · ADC · UART · I²C Clock & reset Conceptual model; RP2040 implements a crossbar and dedicated peripheral blocks. Figure 5.14. RP2040-based embedded system, conceptual block view. The chip-level design is represented here at a teaching level. The EDU PICO board adds the RP2040, flash, power and connected learning devices; the board schematic identifies which on-board device uses which RP2040 interface.Clock and timing conversions used across the chapter From To Calculation Frequency to period Hz → seconds T = 1/f. At 125 MHz, T = 8 ns. Cycles to time cycles → seconds t = N/f. 2 million cycles at 125 MHz → 16 ms. Period to rate seconds → Hz f = 1/T. A 20 ms period → 50 Hz. Samples per interval samples, seconds → samples/s rate = sample count ÷ elapsed seconds.
Use nominal frequencies for textbook calculations and state the assumptions. Real clock tolerance and software overhead affect measurements. Do not assume every peripheral uses clk_sys; for example, the RP2040 ADC uses its own 48 MHz ADC clock.
Practice 5.3 — try before revealing the solution Convert a 2.5 μs period to frequency.
At 125 MHz, how many clock cycles occur in 1 ms?
Worked answer: f = 1/(2.5 × 10⁻⁶) = 400 kHz. Cycles = 125,000,000 × 0.001 = 125,000 cycles.
Read the real RP2040 system diagram Figure 5.15. Official RP2040 system overview: cores, bus fabric, memory, clocks and peripheral blocks. Source: RP2040 datasheet, Figure 2, PDF page 11. Locate Proc0 and Proc1 first: these are the two Cortex-M0+ cores. Follow their connections into the bus fabric, then identify ROM, SRAM and the XIP/cache path. Find the fixed-function controllers such as I²C, SPI, UART, PWM, timer and ADC. Finally locate clock generation, reset and the external GPIO and QSPI interfaces. A block label identifies a capability; it does not mean every board exposes every signal.
Chip resource RP2040 capability Connection to the course Processor cores Two 32-bit Cortex-M0+ cores; rated system-clock operation up to 133 MHz. Use a stated clock such as 125 MHz in calculations; do not assume every runtime uses the same clock. SRAM 264 KiB across six physical banks. Runtime objects, stacks and buffers share this finite working space. GPIO / ADC 30 GPIO signals on the chip; four external ADC inputs share GPIO26–GPIO29. The board’s exposed pins and prewired devices determine usable connections. EDU PICO potentiometer uses GP28. Serial controllers Two UART, two SPI and two I²C controllers. EDU PICO I²C examples use GP5 SCL and GP4 SDA. PWM Eight slices; each contains a counter and two output channels. Channels in one slice share timing settings; 16 channels do not mean 16 independent frequencies. System timer / watchdog Elapsed-time/alarm hardware and a separate recovery watchdog. Distinguish measurement, waveform generation and recovery. PIO / DMA Programmable I/O state machines and hardware data-transfer support. Identify their roles on the diagram; advanced programming is optional enrichment.
Chip, controller board and teaching board are different levels RP2040 is the microcontroller chip; Pico W is the controller board built around it; EDU PICO supplies the teaching peripherals. Pico W wireless connectivity comes from an additional board-level wireless chip, not an RP2040 radio. External flash capacity is also a board choice. These distinctions prevent a photograph, board label or pin table from being mistaken for a universal RP2040 specification.
Diagram analysis — trace potentiometer to LED output Input path: potentiometer voltage → GP28/ADC → peripheral data → runtime value in SRAM. Processing path: core executes the runtime’s scaling and threshold operations. Output path: the NeoPixel library uses the configured GP14 signal to send pixel data. Address/data/control transactions connect the internal blocks; the RGB LED’s power supply is a separate electrical path.
Calculation tutorial — frequency and cycle count Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) t elapsed time or duration (s unless otherwise stated) Ncycles number of clock cycles Example 1 — Find frequency given a period of 2.5 µs Given: Period 0.0000025 s.
f = 1 ÷ T f = 1 ÷ 0.0000025 s f = 400,000 Hz f = 400 kHz
Interpretation: Convert microseconds to seconds before finding hertz.
Example 2 — Find the number of clock cycles in 1 ms at 125 MHz Given: Clock 125 MHz; interval 0.001 s.
Ncycles = f × t Ncycles = 125,000,000 Hz × 0.001 s Ncycles = 125,000
Interpretation: This is clock cycles, not necessarily instructions.
CHAPTER 5 / SUBTOPIC 5.3.1
5.3.1 Program and data memory Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Memory map An assignment of address ranges to memory or peripheral resources. XIP window The system-address region through which external flash can be read and executed. KiB / MiB Binary capacity units: 1 KiB = 1024 bytes; 1 MiB = 1024 KiB. Runtime data Values the program creates or changes while executing, normally held in SRAM. At power-up, RP2040 boot logic starts the device and can load/run firmware from external flash. The CircuitPython firmware and board files are stored in flash. When the interpreter runs, active objects, variables, stack and temporary buffers occupy RAM. The memory map lets a processor access memory and peripheral registers through addresses.
Boot ROM Startup support On-chip · persistent External flash Firmware + CIRCUITPY files Board-level · persistent 264 KiB SRAM Objects · stack · buffers On-chip · volatile CPU + CircuitPython runtime Figure 5.16. Memory roles during CircuitPython operation. The labels distinguish persistent storage from volatile working memory. This conceptual figure does not imply that Python code is loaded as one simple contiguous block.Capacity and alignment calculations Basic equations — choose the equation before calculating Use binary units: 1 KiB = 1024 bytes and 1 MiB = 1,048,576 bytes. Keep all capacity quantities in the same unit. These formulas describe nominal capacity or explicitly specified raw data, not the exact free CircuitPython heap.
What to calculate Basic equation Meaning and units Convert KiB to bytes B = K × 1024
K is capacity in KiB; B is bytes. Convert MiB to bytes B = M × 10242
M is capacity in MiB. Remaining capacity F = C − U − R
C = total, U = used, R = reserved; all in bytes and counted separately. Minimum byte-offset address bits n = ceil(log₂ C), or find the smallest n with 2n ≥ C
C is the number of bytes to identify, not an absolute mapped address. Inclusive address range L = A + C − 1 C = L − A + 1
A = first byte address; L = last byte address, both included. Word size S = W ÷ 8
W = bits per word, a multiple of 8; S = bytes per word. For 32 bits, S = 4. Alignment and padding A mod S = 0 Anext = ceil(A ÷ S) × S padding = Anext − A
mod is the remainder; ceil rounds upward. A_next is the first aligned address at or after A. Successive aligned words Ak = A + k × S
A is an aligned base; k = 0, 1, 2, … . Raw buffer data size Bbuffer = N × S
N = samples; S = specified storage bytes per sample. Add runtime/object overhead separately.
Procedure — use this order for every question Identify what is given and what is required: capacity, remaining bytes, address bits, last address, alignment or buffer size. Write the values with units. Convert KiB or MiB to bytes before combining them; state the stored word/sample width. Choose and write the basic equation. Substitute the values, then calculate. Check rounding and endpoints: round address-bit requirements upward, use +1 for inclusive ranges, and check the alignment remainder. State the answer with units and its limit: nominal storage, minimum offset bits or raw buffer data. Account for firmware, reserved areas or object overhead when specified. Worked example A — Convert capacity and find remaining space Question: Convert 264 KiB of SRAM to bytes. Then, for a separate 2 MiB storage device with 1.5 MiB already used and no additional reserved space, find the remaining capacity in bytes and KiB.
Reveal step-by-step working
B — capacity in bytes
K — capacity in KiB
C — total storage capacity in bytes
U — used storage in bytes
R — additional reserved storage in bytes
F — free storage in bytes 1. Convert the SRAM capacity to bytes One KiB contains 1024 bytes.
B = K × 1024 B = 264 × 1024 B = 270,336 bytes
2. Put the storage-device values in the same unit This is a separate device from the SRAM above. One MiB contains 1,048,576 bytes.
C = 2 × 1,048,576 C = 2,097,152 bytes U = 1.5 × 1,048,576 U = 1,572,864 bytes R = 0 bytes
3. Subtract used and reserved space F = C − U − R F = 2,097,152 − 1,572,864 − 0 F = 524,288 bytes F = 524,288 bytes ÷ (1024 bytes/KiB) F = 512 KiB
Answer: 264 KiB is 270,336 bytes . The separate storage device has 524,288 bytes (512 KiB) free. Subtract any additional reservation if one is specified.
Worked example B — Find the minimum byte-offset address bits Question: Find the minimum number of byte-offset bits required to identify every byte in (i) 2 MiB and (ii) 264 KiB of memory. Assume one byte per addressed location.
Reveal step-by-step working
C — number of byte locations; numerically equal to capacity in bytes here
n — number of byte-offset address bits
2n — number of distinct offsets that n bits can represent 1. Choose the smallest bit width with enough offsets 2n ≥ C
A width is sufficient only when it can represent at least as many offsets as there are byte locations.
2. Calculate the width for 2 MiB C = 2 × 1,048,576 C = 2,097,152 220 = 1,048,576 221 = 2,097,152
Twenty bits are insufficient. Twenty-one bits provide exactly enough offsets, so the minimum is 21 bits .
3. Calculate the width for 264 KiB C = 264 × 1024 C = 270,336 218 = 262,144 219 = 524,288
Eighteen bits are insufficient. Nineteen bits provide enough offsets, although some possible offsets lie outside this memory block.
Answer: 21 byte-offset bits for 2 MiB and 19 byte-offset bits for 264 KiB. These are offsets within a block; they do not change the RP2040’s 32-bit mapped-address architecture.
Worked example C — Align a 32-bit word and find successive addresses Question: A 32-bit word must start on a 4-byte boundary. The next available byte address is 0x20040003. Find the next aligned address, the padding required, and the starting addresses of the first three consecutive words.
Reveal step-by-step working
W — word width in bits
S — word size in bytes
A — available starting byte address
Anext — first aligned address at or above A
P — padding in bytes
k — zero-based word index: 0, 1, 2, …
Ak — starting byte address of word k
mod — remainder after integer division 1. Convert word width to bytes S = W ÷ 8 S = 32 ÷ 8 S = 4 bytes
2. Check alignment and add only the required padding A 4-byte-aligned address has remainder zero when divided by 4. The given address is three bytes beyond the previous boundary.
A mod S = 0x20040003 mod 4 A mod S = 3 P = S − (A mod S) P = 4 − 3 P = 1 byte Anext = A + P Anext = 0x20040003 + 0x1 Anext = 0x20040004
If the address is already aligned, use zero padding; the subtraction above is for a nonzero remainder.
3. Advance by four bytes for each word Ak = Anext + k × S A0 = 0x20040004 + 0x0 A0 = 0x20040004 A1 = 0x20040004 + 0x4 A1 = 0x20040008 A2 = 0x20040004 + 0x8 A2 = 0x2004000C
Answer: Add 1 byte of padding. The first three word starts are 0x20040004, 0x20040008 and 0x2004000C . Each word occupies four consecutive byte addresses.
Important distinction: minimum offset bits describe the capacity of a region. RP2040 uses 32-bit system addresses to locate mapped regions. A 32-bit address space is not a claim that the chip contains 4 GiB of RAM.
RP2040 memory map: location is different from capacity Region Address or range Interpretation Boot ROM base 0x00000000 On-chip startup and support routines. Main XIP window base 0x10000000 Mapped reads from external flash; the installed flash chip determines physical capacity. Standard SRAM window 0x20000000–0x20041FFF 264 KiB; includes the striped main banks and two smaller banks. APB peripheral base 0x40000000 Peripheral control/status registers, not ordinary file storage. AHB-Lite peripheral base 0x50000000 Additional mapped peripheral blocks. SIO base 0xD0000000 Single-cycle I/O register region.
A 32-bit address space can name 2³² byte locations, equivalent to 4 GiB. This is a naming capacity, not a statement that RP2040 contains 4 GiB RAM. Only implemented regions respond as documented; unmapped accesses can fault. The normal CircuitPython course uses board and device APIs rather than raw memory writes.
Six physical SRAM banks and one useful address view The main 256 KiB consists of four 64 KiB banks. A striped address view distributes successive 32-bit words across these banks. Two further banks contain 4 KiB each, giving 256 + 4 + 4 = 264 KiB. The fabric can support simultaneous access to different resources by different bus masters; two cores do not double the physical memory capacity.
B storage capacity (bytes) Afirst first address of the block Alast last inclusive address of the block B = Alast − Afirst + 1 B = 0x20041FFF − 0x20000000 + 1 B = 0x42000 B = 270,336 bytes
RP2040 · 264 KiB SRAM Address view versus physical banks Tap an address to trace its physical bank. The large address region is one contiguous view of four banks; the two small regions select banks 4 and 5 directly.
0x200000000x200000040x200000080x2000000C0x200000100x200400000x20041000
Selected address: 0x20000000 · Physical bank: SRAM0 · Local word index: 0
Figure 5.16a. Six physical SRAM banks presented through the standard 264 KiB address view. The +1 in the inclusive range calculation counts both endpoint bytes. RP2040 reference: Section 2.6.2, Table 153 Flash files, firmware and runtime objects Flash stores persistent firmware and the CIRCUITPY filesystem. The firmware interprets code.py and imports libraries. Active Python objects, temporary values, stacks and buffers consume SRAM. Saving a file successfully therefore does not prove there is enough RAM to execute it. Conversely, changing a variable in RAM does not automatically save that value into a file.
A nominal 2 MiB flash device contains 2,097,152 bytes, but CircuitPython firmware, filesystem structures and reserved areas also occupy storage. The space visible on CIRCUITPY is not the entire flash capacity. Similarly, the interpreter and buffers occupy part of SRAM before a student program creates its variables.
Memory budget — raw buffers versus Python collections A raw array of 1000 unsigned 16-bit samples requires 1000 × 2 = 2000 bytes for its sample data, plus object overhead. A Python list of 1000 numbers need not occupy 2000 bytes: it also stores references and runtime-managed objects. Use the physical-size calculation for explicitly specified packed data, not as an exact heap estimate for arbitrary Python collections.
Practice 5.3.1 — eight questions with worked solutions Try each question using the equation → substitution → calculation → answer-with-units procedure. Reveal the solution only after writing your working.
Practice 1 — Convert binary units Question: Convert 32 KiB, 264 KiB and 2 MiB to bytes.
Reveal step-by-step working 1. Use the conversion factors
K — capacity in KiB
M — capacity in MiB
B — capacity in bytes B = K × 1024 B = M × 10242
2. Convert each quantity 32 KiB = 32 × 1024 bytes 32 KiB = 32,768 bytes 264 KiB = 264 × 1024 bytes 264 KiB = 270,336 bytes 2 MiB = 2 × 10242 bytes 2 MiB = 2,097,152 bytes
Answer: 32 KiB = 32,768 bytes ; 264 KiB = 270,336 bytes ; 2 MiB = 2,097,152 bytes .
Practice 2 — Calculate remaining capacity Question: A 4 MiB device has 2.75 MiB occupied and no additional reservation. Find the remaining capacity in MiB and bytes.
Reveal step-by-step working 1. Write the remaining-capacity equation
C — total capacity in MiB
U — used capacity in MiB
R — additional reserved capacity in MiB
F — remaining capacity in MiB F = C − U − R R = 0 MiB
2. Subtract the occupied space F = 4 MiB − 2.75 MiB − 0 MiB F = 1.25 MiB
3. Convert the answer into bytes F = 1.25 × 10242 bytes F = 1,310,720 bytes
Answer: 1.25 MiB , or 1,310,720 bytes .
Practice 3 — Distinguish offset bits from system-address width Question: Find the minimum byte-offset bits for 4 MiB and 264 KiB. Does either answer mean that RP2040 uses only that many system-address bits?
Reveal step-by-step working 1. Find the minimum width for 4 MiB
C — number of byte locations in the block
b — minimum number of byte-offset bits C = 4 × 10242 C = 4,194,304 bytes 222 = 4,194,304 b = 22 bits
2. Find the minimum width for 264 KiB C = 264 × 1024 C = 270,336 bytes 218 = 262,144 < 270,336 219 = 524,288 ≥ 270,336 b = 19 bits
3. Interpret what the bit counts describe These bits select a byte offset within the specified block. The RP2040 system memory map uses 32-bit addresses to locate regions.
Answer: 22 offset bits for 4 MiB and 19 offset bits for 264 KiB. RP2040 still uses 32-bit mapped system addresses .
Practice 4 — Calculate inclusive memory ranges Question: Use 0x20000000–0x20041FFF to calculate SRAM capacity. Then find the last byte address of a 4 KiB bank starting at 0x20040000.
Reveal step-by-step working 1. Find capacity from the inclusive SRAM range
Afirst — first byte address
Alast — last included byte address
B — number of bytes in the address range B = Alast − Afirst + 1 B = 0x20041FFF − 0x20000000 + 1 B = 0x42000 bytes B = 270,336 bytes B = 264 KiB
2. Find the last address in the 4 KiB bank 4 KiB = 4 × 1024 = 4096 = 0x1000 bytes Alast = Afirst + B − 1 Alast = 0x20040000 + 0x1000 − 1 Alast = 0x20040FFF
Answer: SRAM capacity is 264 KiB (270,336 bytes) . The 4 KiB bank ends at 0x20040FFF .
Practice 5 — Align a 32-bit word and find six-word addresses Question: Align 0x20040003 for 32-bit words. Find the padding, the sixth word’s starting address, and the last occupied byte of six consecutive words.
Reveal step-by-step working 1. Find the word size and next aligned address
S — word size in bytes
A — available starting byte address
P — padding in bytes
Aaligned — first aligned address at or after A S = 32 bits ÷ 8 bits/byte = 4 bytes 0x20040003 mod 4 = 3 P = 4 − 3 = 1 byte Aaligned = 0x20040003 + 1 Aaligned = 0x20040004
2. Find the sixth word start
k — zero-based word index; the sixth word has k = 5 A5 = Aaligned + 5 × S A5 = 0x20040004 + 5 × 4 A5 = 0x20040018
3. Find the last byte occupied by all six words Bsix = 6 × 4 bytes = 24 bytes Alast = Aaligned + Bsix − 1 Alast = 0x20040004 + 24 − 1 Alast = 0x2004001B
Answer: Padding = 1 byte ; sixth word starts at 0x20040018 ; last occupied byte = 0x2004001B .
Practice 6 — Calculate raw sample-buffer size Question: Store 1024 ADC samples as unsigned 16-bit values, although the readings contain 12 significant bits. Find the raw data size in bytes and KiB. Is this an exact Python-list heap estimate?
Reveal step-by-step working 1. Convert the stored width into bytes
W — stored width of each sample in bits
S — storage per sample in bytes S = W ÷ 8 S = 16 ÷ 8 S = 2 bytes/sample
2. Calculate raw data size
N — number of samples
Braw — raw packed sample-data size in bytes Braw = N × S Braw = 1024 × 2 Braw = 2048 bytes Braw = 2048 ÷ 1024 Braw = 2 KiB
3. Interpret the estimate This is the packed sample data only. A Python list also has references and runtime-managed object overhead, so its actual heap use is different.
Answer: Raw packed data = 2048 bytes (2 KiB) . It is not an exact Python-list heap estimate.
Practice 7 — Calculate a reserved flash-storage budget Question: A hypothetical 2 MiB flash device stores 640 KiB of firmware, 32 KiB of filesystem/reserved structures, and 768 KiB of files. The amounts do not overlap. Find the remaining space.
Reveal step-by-step working 1. Write total, used and reserved quantities in KiB
C — total device capacity in KiB
U — firmware and file space in KiB
R — reserved filesystem structures in KiB
F — remaining space in KiB C = 2 × 1024 C = 2048 KiB U = 640 + 768 U = 1408 KiB R = 32 KiB
2. Subtract used and reserved capacity F = C − U − R F = 2048 − 1408 − 32 F = 608 KiB
3. Convert free space into bytes F = 608 × 1024 bytes F = 622,592 bytes
Answer: Remaining capacity = 608 KiB (622,592 bytes) .
Practice 8 — Calculate SRAM capacity and striped word routing Question: Calculate total capacity from four 64 KiB banks and two 4 KiB banks. In the striped view, a zero-based word index of 7 is in the 256 KiB region starting at 0x20000000. Find its system address, physical bank, and local word index.
Reveal step-by-step working 1. Add the capacities of the six banks
Btotal — total SRAM capacity
Blarge — capacity of each large bank
Bsmall — capacity of each small bank Btotal = 4 × 64 KiB + 2 × 4 KiB Btotal = 256 KiB + 8 KiB Btotal = 264 KiB Btotal = 264 × 1024 Btotal = 270,336 bytes
2. Route word index 7 to a system address
w — zero-based 32-bit word index
Abase — base address of the striped SRAM region
S — size of each word in bytes S = 32 bits ÷ 8 = 4 bytes A = Abase + w × S A = 0x20000000 + 7 × 4 A = 0x2000001C
3. Find physical bank and local word index physical bank = w mod 4 physical bank = 7 mod 4 = SRAM3 local word index = floor(w ÷ 4) local word index = floor(7 ÷ 4) = 1
Answer: Total SRAM = 264 KiB . Word 7 maps to 0x2000001C , physical bank SRAM3 , local word index 1 .
Calculation tutorial — packed storage Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Ns number of samples Bsample bytes per packed sample Btotal total storage (bytes) fs sampling frequency (samples/s) t elapsed time or duration (s unless otherwise stated) Example 1 — Find the raw storage required for 1000 packed 16-bit samples Given: Each packed sample occupies two bytes.
Btotal = Ns × Bsample Btotal = 1000 × 2 bytes Btotal = 2000 bytes
Interpretation: Container and runtime overhead require additional memory.
Example 2 — Find the sample count and raw storage for 10 s at 100 samples/s using two bytes per sample, excluding the final endpoint Given: 100 samples/s; ten seconds; two bytes per sample.
Ns = fs × t Ns = 100 samples/s × 10 s Ns = 1000 Btotal = Ns × Bsample Btotal = 1000 × 2 bytes Btotal = 2000 bytes
Interpretation: This counts samples from time zero up to, but excluding, the final endpoint.
CHAPTER 5 / SUBTOPIC 5.3.2
5.3.2 Timers and counters Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Timer A counter driven from a clock or timebase, used to measure elapsed time or trigger events. Alarm A comparison event that requests an interrupt when a programmed time is reached. PWM TOP The terminal count value at which a PWM counter wraps; normal-mode period contains TOP + 1 counter counts. Divider A factor that reduces a clock’s effective rate before it advances a counter. Duty cycle The percentage of a period during which a digital output is HIGH. RP2040 has a 64-bit system timer that increments once per microsecond and four alarm comparators that match the low 32 bits. Separately, its PWM block has eight slices with 16-bit counters; each slice can drive two outputs. This means timer and PWM calculations share ideas but have different hardware roles.
Calculation method for this topic For every example: identify the given values → write the equation → convert units → substitute → calculate → round only where an integer setting is required → check the range and interpret the result.
Use 1 MHz = 1,000,000 Hz; 1 kHz = 1000 Hz; 1 ms = 0.001 s; 1 μs = 0.000001 s; 1 ns = 0.000000001 s. Keep clock rates in Hz and times in seconds until converting the final answer.
1. System timer and alarm arithmetic One timer tick = 1 μs. For an interval in seconds, convert to microseconds: ticks = seconds × 1,000,000. In a low-level alarm example, alarm_time = current_time_us + delay_us. The alarm compares the low 32 bits, so a single scheduled future interval is limited to less than 2³² μs, about 4,295 s or 71.6 min. CircuitPython application code normally uses time.monotonic(), time.sleep() or alarm APIs rather than writing these registers directly.
Worked calculation: timer and alarm Atarget target timer count Anow current timer count mod integer remainder after division N number of timer ticks t elapsed time or duration (s unless otherwise stated) N = t × 106 Atarget = (Anow + N) mod 232
Given interval = 250 ms, timer tick = 1 μs and current low timer word = 8,000,000 μs. Convert the interval:
t elapsed time or duration (s unless otherwise stated) t = 250 ÷ 1000 = 0.250 s
Substitute:
N number of timer ticks N = 0.250 × 1,000,000 = 250,000 ticks
Each tick is one microsecond.
Add the delay: 8,000,000 + 250,000 = 8,250,000 μs. The sum is below 2³², so no low-word wrap occurs. The alarm target is 8,250,000; it is an absolute low timer value, not a delay of 8.25 s. Practice set — System timer and alarms Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Timer ticks Convert 375 ms into system-timer ticks when each tick is 1 μs.
ftick timer tick rate (ticks/s) N number of timer ticks t elapsed time or duration (s unless otherwise stated) N = t × ftick
Reveal step-by-step solution Identify values and convert units. ftick timer tick rate (ticks/s) t elapsed time or duration (s unless otherwise stated) t = 375 ms = 0.375 s ftick = 1,000,000 ticks/s
Write the equation. ftick timer tick rate (ticks/s) N number of timer ticks t elapsed time or duration (s unless otherwise stated) N = t × ftick
Substitute and calculate. N number of timer ticks N = 0.375 × 1,000,000 = 375,000
State the answer and check its meaning. 375,000 ticks; equivalently 375,000 μs.
Practice 2 — Elapsed time from ticks A timer advances by 2,400,000 ticks at 1 μs per tick. Find elapsed seconds.
Ttick duration of one timer tick (s) Δt elapsed time interval (s) N number of timer ticks Δt = N × Ttick
Reveal step-by-step solution Identify values and convert units. Ttick duration of one timer tick (s) N number of timer ticks N = 2,400,000 Ttick = 0.000001 s
Write the equation. Ttick duration of one timer tick (s) Δt elapsed time interval (s) N number of timer ticks Δt = N × Ttick
Substitute and calculate. Δt elapsed time interval (s) Δt = 2,400,000 × 0.000001 = 2.4 s
State the answer and check its meaning. Elapsed time is 2.4 s.
Practice 3 — Future alarm target The current low timer word is 12,000,000 μs. Schedule an alarm 80 ms ahead. Find the target.
Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Atarget = (Anow + Ntick ) mod 232
Reveal step-by-step solution Identify values and convert units. Anow current timer count delay requested delay in the stated time/count unit Anow = 12,000,000 μs delay = 80 ms = 80,000 μs
Write the equation. Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Atarget = (Anow + Ntick ) mod 232
Substitute and calculate. Atarget target timer count mod integer remainder after division Atarget = (12,000,000 + 80,000) mod 4,294,967,296 = 12,080,000
State the answer and check its meaning. Target = 12,080,000; no low-word wrap occurs.
Practice 4 — Remaining alarm delay The current low timer value is 5,000,000 and a future target is 5,250,000. Find the remaining delay in ms.
Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Ntick = (Atarget − Anow ) mod 232
Reveal step-by-step solution Identify values and convert units. Atarget target timer count Anow current timer count Anow = 5,000,000 Atarget = 5,250,000 1000 μs = 1 ms
Write the equation. Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Ntick = (Atarget − Anow ) mod 232
Substitute and calculate. Ntick number of timer ticks Ntick = 5,250,000 − 5,000,000 = 250,000 delayms = 250,000 ÷ 1000 = 250
State the answer and check its meaning. Remaining delay = 250 ms, assuming this target is in the intended future interval.
2. PWM counter frequency and TOP In normal edge-aligned mode, fPWM = fPWM-clock ÷ (TOP + 1), where fPWM-clock = f_sys ÷ divider. Therefore, TOP = f_sys ÷ (divider × fPWM) − 1. TOP is a count limit, not time in seconds. Because the counter is 16-bit, TOP ranges from 0 to 65,535 in this mode. A divider may be fractional in RP2040 PWM hardware; classroom worked examples may choose convenient valid settings.
Worked calculation: 20 kHz PWM from a 125 MHz system clock fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) T period of one cycle (s unless another time unit is stated) D PWM clock-divider setting (dimensionless; not duty percentage) C counter counts per PWM period C = fsys ÷ (D × fPWM ) TOP = C − 1 T = 1 ÷ fPWM
Given
fsys system-clock frequency (Hz) fsys = 125 MHz
, divider
D PWM clock-divider setting (dimensionless; not duty percentage) D = 1
and requested
fPWM PWM output frequency (Hz) fPWM = 20 kHz
; use normal edge-aligned mode.
Convert units:
fsys system-clock frequency (Hz) fsys = 125,000,000 Hz
and
fPWM PWM output frequency (Hz) fPWM = 20,000 Hz
Find counts:
C counter counts per PWM period C = 125,000,000 ÷ (1 × 20,000) = 6250
counts per period.
The counter includes zero, so
TOP PWM counter upper limit (count) C counter counts per PWM period TOP = C − 1 = 6250 − 1 = 6249
Check the setting: 0 ≤ 6249 ≤ 65,535, so TOP fits the 16-bit counter. Verify frequency:
factual realized frequency (Hz) factual = 125,000,000 ÷ [1 × (6249 + 1)] = 20,000 Hz
Find the period:
T period of one cycle (s unless another time unit is stated) T = 1 ÷ 20,000 = 0.000050 s
; multiply by 10^6 to obtain 50 μs.
Practice set — PWM counter frequency and TOP Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Counter clock At f_sys = 125 MHz and divider 5, find the PWM counter rate.
fcounter PWM counter clock (Hz) fsys system-clock frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) fcounter = fsys ÷ D
Reveal step-by-step solution Identify values and convert units. fsys system-clock frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) fsys = 125,000,000 Hz D = 5
Write the equation. fcounter PWM counter clock (Hz) fsys system-clock frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) fcounter = fsys ÷ D
Substitute and calculate. fcounter PWM counter clock (Hz) fcounter = 125,000,000 ÷ 5 = 25,000,000 Hz
State the answer and check its meaning. Counter rate = 25 MHz.
Practice 2 — Calculate TOP Find TOP for 10 kHz normal-mode PWM at f_sys = 125 MHz and divider 5.
fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) TOP = fsys ÷ (D × fPWM ) − 1
Reveal step-by-step solution Identify values and convert units. fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) fsys = 125,000,000 Hz D = 5 fPWM = 10,000 Hz
Write the equation. fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) TOP = fsys ÷ (D × fPWM ) − 1
Substitute and calculate. TOP PWM counter upper limit (count) TOP = 125,000,000 ÷ (5 × 10,000) − 1 = 2500 − 1 = 2499
State the answer and check its meaning. TOP = 2499, within the 16-bit range.
Practice 3 — Frequency from settings Find the normal-mode frequency for
fsys system-clock frequency (Hz) fsys = 125 MHz
, divider 2 and
TOP PWM counter upper limit (count) TOP = 12,499
fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) fPWM = fsys ÷ [D × (TOP + 1)]
Reveal step-by-step solution Identify values and convert units. fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) fsys = 125,000,000 Hz D = 2 TOP + 1 = 12,500
Write the equation. fsys system-clock frequency (Hz) fPWM PWM output frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) fPWM = fsys ÷ [D × (TOP + 1)]
Substitute and calculate. fPWM PWM output frequency (Hz) fPWM = 125,000,000 ÷ (2 × 12,500) = 5000 Hz
State the answer and check its meaning. Output frequency = 5 kHz.
Practice 4 — Period from settings Find the PWM period for
fsys system-clock frequency (Hz) fsys = 125 MHz
, divider 4 and
TOP PWM counter upper limit (count) TOP = 31,249
fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) T period of one cycle (s unless another time unit is stated) D PWM clock-divider setting (dimensionless; not duty percentage) T = (TOP + 1) × D ÷ fsys
Reveal step-by-step solution Identify values and convert units. fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) TOP + 1 = 31,250 D = 4 fsys = 125,000,000 Hz
Write the equation. fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) T period of one cycle (s unless another time unit is stated) D PWM clock-divider setting (dimensionless; not duty percentage) T = (TOP + 1) × D ÷ fsys
Substitute and calculate. T period of one cycle (s unless another time unit is stated) s shaft speed (revolutions/minute, rpm) T = 31,250 × 4 ÷ 125,000,000 = 0.001 s = 1 ms
State the answer and check its meaning. Period = 1 ms.
3. Duty cycle and pulse width duty (%) = high-time ÷ period × 100. At register level, approximate duty (%) = compare ÷ (TOP+1) × 100. CircuitPython uses a 16-bit duty value from 0 to 65,535; approximately duty_cycle = percentage × 65,535 ÷ 100. At 40%, this is 26,214. The internal resolution may be lower for a chosen frequency because frequency and duty share the PWM counter.
Worked calculation: 40% duty on the CircuitPython scale round round to the nearest integer p percentage on a 0–100 scale (%) u integer CircuitPython duty setting, from 0 to 65,535 r dimensionless ratio in PWM calculations; CircuitPython ADC reading in ADC calculations r = p ÷ 100 u ≈ round(r × 65,535)
Given duty = 40% and the API maximum = 65,535. Convert percent to a fraction:
r dimensionless ratio in PWM calculations; CircuitPython ADC reading in ADC calculations r = 40 ÷ 100 = 0.40
Scale: 0.40 ×
. Round to the integer
u integer CircuitPython duty setting, from 0 to 65,535 u = 26,214
For a 50 μs period,
TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) r dimensionless ratio in PWM calculations; CircuitPython ADC reading in ADC calculations TON = r × T = 0.40 × 50 = 20
μs. This API value is not the PWM TOP register.
Worked calculation: 50 Hz servo timing with divider 64 fcounter PWM counter clock (Hz) compare PWM HIGH compare count fsys system-clock frequency (Hz) round round to the nearest integer TON HIGH time within one period (same time unit as T) TOP PWM counter upper limit (count) T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) D PWM clock-divider setting (dimensionless; not duty percentage) C counter counts per PWM period T = 1 ÷ f fcounter = fsys ÷ D C = fcounter × T TOP = C − 1 compare ≈ round(fcounter × TON )
Given
f frequency (Hz, cycles per second) f = 50 Hz
,
fsys system-clock frequency (Hz) fsys = 125 MHz
,
D PWM clock-divider setting (dimensionless; not duty percentage) D = 64
and desired
TON HIGH time within one period (same time unit as T) TON = 1.5 ms
Convert units:
fsys system-clock frequency (Hz) fsys = 125,000,000 Hz
and
TON HIGH time within one period (same time unit as T) TON = 0.0015 s
Find the frame:
T period of one cycle (s unless another time unit is stated) s shaft speed (revolutions/minute, rpm) T = 1 ÷ 50 = 0.020 s = 20 ms
Find counter rate:
fcounter PWM counter clock (Hz) fcounter = 125,000,000 ÷ 64 = 1,953,125
counts/s.
Ideal period counts:
C counter counts per PWM period C = 1,953,125 × 0.020 = 39,062.5
. Choose 39,062 counts for this illustrative setting;
TOP PWM counter upper limit (count) TOP = 39,061
Check the choice: TOP fits 16 bits.
factual realized frequency (Hz) factual = 1,953,125 ÷ 39,062 ≈ 50.00064 Hz
Pulse counts = 1,953,125 ×
; round to
compare PWM HIGH compare count compare = 2930
counts.
Actual HIGH time ≈ 2930 ÷
s shaft speed (revolutions/minute, rpm) 1,953,125 = 0.00150016 s = 1.50016 ms
The small difference is quantization; this register example is separate from the API duty scale.
Practice set — Duty cycle and pulse width Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Duty percentage An output is HIGH for 3 μs in a 12 μs period. Find duty percentage.
TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) p = TON ÷ T × 100
Reveal step-by-step solution Identify values and convert units. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) TON = 3 μs T = 12 μs use matching units
Write the equation. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) p = TON ÷ T × 100
Substitute and calculate. p percentage on a 0–100 scale (%) p = 3 ÷ 12 × 100 = 25%
State the answer and check its meaning. Duty = 25%.
Practice 2 — HIGH time A waveform has 35% duty and a 40 μs period. Find its HIGH time.
TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) TON = p ÷ 100 × T
Reveal step-by-step solution Identify values and convert units. T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) p = 35 T = 40 μs
Write the equation. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) TON = p ÷ 100 × T
Substitute and calculate. TON HIGH time within one period (same time unit as T) TON = 35 ÷ 100 × 40 = 14 μs
State the answer and check its meaning. HIGH time = 14 μs.
Practice 3 — Compare level For normal PWM with TOP = 999, estimate the compare count for 30% duty.
compare PWM HIGH compare count round round to the nearest integer TOP PWM counter upper limit (count) p percentage on a 0–100 scale (%) compare ≈ round(p ÷ 100 × (TOP + 1))
Reveal step-by-step solution Identify values and convert units. TOP PWM counter upper limit (count) p percentage on a 0–100 scale (%) p = 30 TOP + 1 = 1000
Write the equation. compare PWM HIGH compare count round round to the nearest integer TOP PWM counter upper limit (count) p percentage on a 0–100 scale (%) compare ≈ round(p ÷ 100 × (TOP + 1))
Substitute and calculate. compare PWM HIGH compare count round round to the nearest integer compare ≈ round(0.30 × 1000) = 300
State the answer and check its meaning. Compare ≈ 300 counts; this is a register-level value, not a duty_cycle API value.
Practice 4 — Duty from an API value Estimate duty percentage for CircuitPython duty_cycle = 16,384.
p percentage on a 0–100 scale (%) u integer CircuitPython duty setting, from 0 to 65,535 p ≈ u ÷ 65,535 × 100
Reveal step-by-step solution Identify values and convert units. u integer CircuitPython duty setting, from 0 to 65,535 u = 16,384 API maximum = 65,535
Write the equation. p percentage on a 0–100 scale (%) u integer CircuitPython duty setting, from 0 to 65,535 p ≈ u ÷ 65,535 × 100
Substitute and calculate. p percentage on a 0–100 scale (%) p ≈ 16,384 ÷ 65,535 × 100 ≈ 25.0004%
State the answer and check its meaning. Approximately 25%; the API-scale estimate does not imply exact physical resolution.
4. Clock synthesis: 12 MHz crystal to 125 MHz system clock The crystal provides a stable reference; the PLL (phase-locked loop) multiplies that reference to a much higher VCO frequency, then post-dividers reduce it to a useful system clock. This is why 12 MHz can produce 125 MHz: the PLL does not simply multiply by 125 to produce the final system clock.
Worked calculation: RP2040 system PLL fPLLref frequency at the PLL reference input (Hz) POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) REFDIV PLL reference divider (dimensionless) fXOSC external crystal frequency (Hz) fVCO PLL voltage-controlled oscillator frequency (Hz) FBDIV PLL feedback multiplier (dimensionless) fout PLL output frequency (Hz) fPLLref = fXOSC ÷ REFDIV fVCO = fPLLref × FBDIV fout = fVCO ÷ (POSTDIV1 × POSTDIV2)
Given
fXOSC external crystal frequency (Hz) fXOSC = 12 MHz
,
POSTDIV1 first PLL post-divider (dimensionless) REFDIV PLL reference divider (dimensionless) FBDIV PLL feedback multiplier (dimensionless) REFDIV = 1, FBDIV = 125, POSTDIV1 = 6
and
POSTDIV2 second PLL post-divider (dimensionless) POSTDIV2 = 2
Keep all frequencies in MHz.
Reference frequency:
fPLLref frequency at the PLL reference input (Hz) fPLLref = 12 ÷ 1 = 12 MHz
Multiply feedback:
fVCO PLL voltage-controlled oscillator frequency (Hz) fVCO = 12 × 125 = 1500 MHz
Check the VCO: 750 ≤ 1500 ≤ 1600 MHz, so this value is within the permitted range. Combined post-divider = 6 ×
. Output
fout PLL output frequency (Hz) fout = 1500 ÷ 12 = 125 MHz
Check: 12 ≥ 5 MHz, FBDIV 125 fits 16–320, both post-dividers fit 1–7 and 125 ≤ 133 MHz. The 125 feedback multiplier is not the final clock until the post-division is applied. Hardware setting limits: For legal settings, the datasheet specifies FBDIV 16–320, each post-divider 1–7, reference frequency at least 5 MHz, VCO 750–1,600 MHz, and system PLL output no higher than 133 MHz. The clock generator then selects the PLL output as clk_sys.
Practice set — PLL clock synthesis Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — PLL reference With
fXOSC external crystal frequency (Hz) fXOSC = 12 MHz
and
REFDIV PLL reference divider (dimensionless) REFDIV = 2,
find the PLL reference frequency and check its 5 MHz minimum.
fPLLref frequency at the PLL reference input (Hz) REFDIV PLL reference divider (dimensionless) fXOSC external crystal frequency (Hz) fPLLref = fXOSC ÷ REFDIV
Reveal step-by-step solution Identify values and convert units. REFDIV PLL reference divider (dimensionless) fXOSC external crystal frequency (Hz) fXOSC = 12 MHz REFDIV = 2
Write the equation. fPLLref frequency at the PLL reference input (Hz) REFDIV PLL reference divider (dimensionless) fXOSC external crystal frequency (Hz) fPLLref = fXOSC ÷ REFDIV
Substitute and calculate. fPLLref frequency at the PLL reference input (Hz) fPLLref = 12 ÷ 2 = 6 MHz 6 ≥ 5
State the answer and check its meaning. Reference = 6 MHz; other PLL limits still need checking.
Practice 2 — VCO frequency For a 12 MHz PLL reference and FBDIV = 64, find VCO frequency and check 750–1600 MHz.
fPLLref frequency at the PLL reference input (Hz) fVCO PLL voltage-controlled oscillator frequency (Hz) FBDIV PLL feedback multiplier (dimensionless) fVCO = fPLLref × FBDIV
Reveal step-by-step solution Identify values and convert units. fPLLref frequency at the PLL reference input (Hz) FBDIV PLL feedback multiplier (dimensionless) fPLLref = 12 MHz FBDIV = 64
Write the equation. fPLLref frequency at the PLL reference input (Hz) fVCO PLL voltage-controlled oscillator frequency (Hz) FBDIV PLL feedback multiplier (dimensionless) fVCO = fPLLref × FBDIV
Substitute and calculate. fVCO PLL voltage-controlled oscillator frequency (Hz) fVCO = 12 × 64 = 768 MHz 750 ≤ 768 ≤ 1600
State the answer and check its meaning. VCO = 768 MHz, within the permitted range.
Practice 3 — Post-divided output A VCO runs at 768 MHz;
POSTDIV1 first PLL post-divider (dimensionless) POSTDIV1 = 4
and
POSTDIV2 second PLL post-divider (dimensionless) POSTDIV2 = 4
Find the PLL output.
POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) fVCO PLL voltage-controlled oscillator frequency (Hz) fout PLL output frequency (Hz) fout = fVCO ÷ (POSTDIV1 × POSTDIV2)
Reveal step-by-step solution Identify values and convert units. fVCO PLL voltage-controlled oscillator frequency (Hz) fVCO = 768 MHz combined division = 4 × 4 = 16
Write the equation. POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) fVCO PLL voltage-controlled oscillator frequency (Hz) fout PLL output frequency (Hz) fout = fVCO ÷ (POSTDIV1 × POSTDIV2)
Substitute and calculate. fout PLL output frequency (Hz) fout = 768 ÷ 16 = 48 MHz
State the answer and check its meaning. PLL output = 48 MHz.
Practice 4 — Required feedback multiplier Find FBDIV for 120 MHz output with a 12 MHz reference,
POSTDIV1 first PLL post-divider (dimensionless) POSTDIV1 = 5
and
POSTDIV2 second PLL post-divider (dimensionless) POSTDIV2 = 2
Check VCO.
fPLLref frequency at the PLL reference input (Hz) POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) FBDIV PLL feedback multiplier (dimensionless) fout PLL output frequency (Hz) FBDIV = fout × POSTDIV1 × POSTDIV2 ÷ fPLLref
Reveal step-by-step solution Identify values and convert units. fPLLref frequency at the PLL reference input (Hz) POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) fout PLL output frequency (Hz) fout = 120 MHz fPLLref = 12 MHz POSTDIV1 × POSTDIV2 = 10
Write the equation. fPLLref frequency at the PLL reference input (Hz) POSTDIV1 first PLL post-divider (dimensionless) POSTDIV2 second PLL post-divider (dimensionless) FBDIV PLL feedback multiplier (dimensionless) fout PLL output frequency (Hz) FBDIV = fout × POSTDIV1 × POSTDIV2 ÷ fPLLref
Substitute and calculate. fVCO PLL voltage-controlled oscillator frequency (Hz) FBDIV PLL feedback multiplier (dimensionless) FBDIV = 120 × 10 ÷ 12 = 100 fVCO = 12 × 100 = 1200 MHz
State the answer and check its meaning. FBDIV PLL feedback multiplier (dimensionless) FBDIV = 100
; VCO = 1200 MHz. Divider and system-clock limits are satisfied in this example.
5. Other RP2040 calculations: ADC sampling and voltage The RP2040 ADC hardware is 12-bit and specified up to 500 ksample/s under the datasheet’s stated clock conditions. Ideal quantization has 2¹² = 4,096 code levels. A simple estimate is code ≈ Vin/Vref × 4095 and Vin ≈ code/4095 × Vref. The RP2040 hardware conversion is 12-bit, but CircuitPython analogio.AnalogIn.value presents the reading on a 0–65,535 (16-bit) API scale even when the hardware ADC has fewer bits. The extra numeric range does not add physical resolution. For the API reading, estimate voltage using V ≈ value/65535 × reference_voltage; use the 12-bit formula only when a question explicitly asks for the raw ADC code. CircuitPython’s reference_voltage property reports the configured maximum measurable voltage; board and wiring assumptions still matter.
Worked calculation: ADC quantization estimate at 3.3 V reference Vref reference voltage (V) kmax largest raw ADC code round round to the nearest integer Vin input voltage (V) code raw ADC code step ideal ADC voltage-bin width (V) n counter or address width (bits) L number of distinct code levels or addressed locations L = 2n kmax = 2n − 1 code ≈ round(Vin ÷ Vref × kmax ) step ≈ Vref ÷ L
Given
n counter or address width (bits) n = 12 bits
,
Vin input voltage (V) Vin = 1.65 V
and
Vref reference voltage (V) Vref = 3.3 V
Count L: 2^
. Maximum raw
code raw ADC code code = 4096 − 1 = 4095
Input fraction: V_in ÷
Vref reference voltage (V) Vref = 1.65 ÷ 3.3 = 0.5
Endpoint-scale estimate:
round round to the nearest integer code raw ADC code code ≈ round(0.5 × 4095) = round(2047.5) = 2048
Ideal hardware
step ideal ADC voltage-bin width (V) step = 3.3 ÷ 4096 = 0.000805664 V
Multiply by 1000: approximately 0.806 mV per code.
Ideal API-scale estimate ≈ round(0.5 × 65,535) = 32,768. Actual analogio.value depends on the quantized reading and port scaling; this is not extra ADC resolution. Using that illustrative API value,
V voltage (V) V ≈ 32,768 ÷ 65,535 × 3.3 = 1.65003 V
Real readings also depend on noise and reference accuracy.
Worked calculation: ADC conversion rate and 1 ksample/s pacing pacingcycles ADC clock cycles between conversion starts fsample requested ADC sampling rate (samples/s) DIV.INT integer part of the ADC pacing-divider register tconv ADC conversion duration (s) cycles clock cycles per conversion or operation as stated fADC ADC clock frequency (Hz) fmax maximum conversion rate (samples/s) tconv = cycles ÷ fADC fmax = 1 ÷ tconv pacingcycles = fADC ÷ fsample DIV.INT = pacingcycles − 1
Given
fADC ADC clock frequency (Hz) fADC = 48 MHz = 48,000,000 Hz
and 96 clock cycles per conversion.
Conversion time = 96 ÷
s shaft speed (revolutions/minute, rpm) 48,000,000 = 0.000002 s = 2
μs.
Maximum conversion rate in this model = 1 ÷
s shaft speed (revolutions/minute, rpm) 0.000002 = 500,000 samples/s = 500
ksample/s.
For
fsample requested ADC sampling rate (samples/s) fsample = 1
ksample/
s shaft speed (revolutions/minute, rpm) s = 1000 samples/s
, the requested interval = 1 ÷
s shaft speed (revolutions/minute, rpm) 1000 = 0.001 s = 1 ms
Pacing
cycles clock cycles per conversion or operation as stated cycles = 48,000,000 ÷ 1000 = 48,000
. Because the trigger uses DIV.INT + 1, choose
DIV.INT integer part of the ADC pacing-divider register DIV.INT = 48,000 − 1 = 47,999
Check: 48,000 cycles allow time for a 96-cycle conversion. Verify 48,000,000 ÷ (47,999 + 1) = 1000 samples/s. CircuitPython normally hides this register configuration. Practice set — ADC voltage, quantization and pacing Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Raw ADC code Estimate a 12-bit raw ADC code for
Vin input voltage (V) Vin = 0.66 V
and
Vref reference voltage (V) Vref = 3.3 V
Vref reference voltage (V) round round to the nearest integer Vin input voltage (V) raw raw ADC code raw ≈ round(Vin ÷ Vref × (212 − 1))
Reveal step-by-step solution Identify values and convert units. Vref reference voltage (V) Vin input voltage (V) code raw ADC code raw raw ADC code Vin = 0.66 V Vref = 3.3 V maximum raw code = 4095
Write the equation. Vref reference voltage (V) round round to the nearest integer Vin input voltage (V) raw raw ADC code raw ≈ round(Vin ÷ Vref × (212 − 1))
Substitute and calculate. round round to the nearest integer raw raw ADC code raw ≈ round(0.66 ÷ 3.3 × 4095) = round(819) = 819
State the answer and check its meaning. Estimated raw code = 819, within 0–4095.
Practice 2 — Voltage from the API reading Given analogio.
value CircuitPython ADC API reading value = 49,152
and
referencevoltage ADC reference voltage (V) referencevoltage = 3.3 V
, estimate input voltage.
referencevoltage ADC reference voltage (V) value CircuitPython ADC API reading V voltage (V) V ≈ value ÷ 65,535 × referencevoltage
Reveal step-by-step solution Identify values and convert units. referencevoltage ADC reference voltage (V) value CircuitPython ADC API reading value = 49,152 referencevoltage = 3.3 V
Write the equation. referencevoltage ADC reference voltage (V) value CircuitPython ADC API reading V voltage (V) V ≈ value ÷ 65,535 × referencevoltage
Substitute and calculate. V voltage (V) V ≈ 49,152 ÷ 65,535 × 3.3 ≈ 2.47504 V
State the answer and check its meaning. Voltage ≈ 2.475 V; use the API denominator, not the raw 12-bit denominator.
Practice 3 — Ideal voltage step Find the ideal hardware voltage step for a 12-bit ADC with 3.3 V reference, in mV.
Vref reference voltage (V) ΔV ideal ADC voltage-bin width (V) n counter or address width (bits) ΔV ≈ Vref ÷ 2n
Reveal step-by-step solution Identify values and convert units. Vref reference voltage (V) n counter or address width (bits) L number of distinct code levels or addressed locations n = 12 212 = 4096 L Vref = 3.3 V
Write the equation. Vref reference voltage (V) ΔV ideal ADC voltage-bin width (V) n counter or address width (bits) ΔV ≈ Vref ÷ 2n
Substitute and calculate. ΔV ideal ADC voltage-bin width (V) ΔV ≈ 3.3 ÷ 4096 = 0.000805664 V ×1000 ≈ 0.805664 mV
State the answer and check its meaning. Approximately 0.806 mV per hardware code; this is not a guarantee of ADC accuracy.
Practice 4 — ADC pacing divider At a 48 MHz ADC clock, find DIV.INT for 2 ksample/s pacing with no fractional part.
fsample requested ADC sampling rate (samples/s) DIV.INT integer part of the ADC pacing-divider register fADC ADC clock frequency (Hz) DIV.INT = fADC ÷ fsample − 1
Reveal step-by-step solution Identify values and convert units. fsample requested ADC sampling rate (samples/s) fADC ADC clock frequency (Hz) fADC = 48,000,000 Hz fsample = 2000 samples/s
Write the equation. fsample requested ADC sampling rate (samples/s) DIV.INT integer part of the ADC pacing-divider register fADC ADC clock frequency (Hz) DIV.INT = fADC ÷ fsample − 1
Substitute and calculate. DIV.INT integer part of the ADC pacing-divider register cycles clock cycles per conversion or operation as stated cycles = 48,000,000 ÷ 2000 = 24,000 DIV.INT = 24,000 − 1 = 23,999
State the answer and check its meaning. DIV.INT = 23,999. The 24,000-cycle interval is longer than the 96-cycle conversion.
Mixed review — timer, PWM, duty and ADC A 1.25 s interval is expressed in system-timer microsecond ticks.
Calculate TOP for 10 kHz PWM when
fsys system-clock frequency (Hz) fsys = 125 MHz
and divider = 2.
At 25% duty on a 20 ms period, find the pulse HIGH time.
Estimate the ideal 12-bit ADC code for 0.825 V with Vref = 3.3 V.
Reveal step-by-step solutions Practice 5.3.2 — worked solution 1: timer ticks N number of timer ticks t elapsed time or duration (s unless otherwise stated) N = t × 106
Given t = 1.25 s and 1 μs timer ticks. Substitute
N number of timer ticks N = 1.25 × 1,000,000 = 1,250,000 ticks
The interval equals 1,250,000 μs.
Practice 5.3.2 — worked solution 2: PWM TOP fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) f frequency (Hz, cycles per second) D PWM clock-divider setting (dimensionless; not duty percentage) C counter counts per PWM period C = fsys ÷ (D × f) TOP = C − 1
Given
fsys system-clock frequency (Hz) fsys = 125 MHz = 125,000,000 Hz
,
D PWM clock-divider setting (dimensionless; not duty percentage) D = 2
and
f frequency (Hz, cycles per second) f = 10 kHz = 10,000 Hz
C counter counts per PWM period C = 125,000,000 ÷ (2 × 10,000) = 6250
.
TOP PWM counter upper limit (count) TOP = 6250 − 1 = 6249
Check range: TOP fits. Recalculate 125,000,000 ÷ [2 × (6249 + 1)] = 10,000 Hz. Practice 5.3.2 — worked solution 3: HIGH time TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) p percentage on a 0–100 scale (%) TON = p ÷ 100 × T
Given duty = 25% and period
T period of one cycle (s unless another time unit is stated) T = 20 ms
Convert percent: 25 ÷
. Substitute
TON HIGH time within one period (same time unit as T) TON = 0.25 × 20 ms = 5 ms
Check: 5 ÷ 20 × 100 = 25%. This is a duty calculation, not a normal servo position command. Practice 5.3.2 — worked solution 4: ADC code Vref reference voltage (V) round round to the nearest integer Vin input voltage (V) code raw ADC code code ≈ round(Vin ÷ Vref × (212 − 1))
Given
Vin input voltage (V) Vin = 0.825 V
,
Vref reference voltage (V) Vref = 3.3 V
and 12-bit raw hardware code.
Maximum
code raw ADC code code = 212 − 1 = 4095
. Input fraction = 0.825 ÷
Unrounded estimate = 0.25 ×
Round to approximately 1024, within 0–4095.
Common calculation errors Using TOP instead of TOP+1 for normal PWM count totals. Mixing kHz with Hz or ms with seconds. Calling TOP a frequency or time value; it is the terminal counter count. Assuming the requested CircuitPython PWM frequency is exact; inspect pwm.frequency. Assuming a servo uses 50% duty; servo position is encoded by pulse width. Using 4096 as the maximum code rather than 4095 in the 12-bit endpoint formula. Applying RP2040 register equations to the old PIC16F877A timer without re-deriving its clock and prescaler chain. API boundary: in normal CircuitPython programs, pwmio.PWMOut(pin, frequency=..., duty_cycle=...) asks for frequency and duty. CircuitPython chooses available hardware settings; TOP and divider are explanatory hardware calculations, not direct PWMOut constructor parameters.
Timer, counter, PWM and watchdog: choose the correct job Resource What advances it Purpose System timer One-microsecond timebase. Measure elapsed time and schedule alarm comparisons. Event counter, concept An accepted external event or edge. Count presses, revolutions or pulses; the acquisition method limits the observable rate. PWM slice System clock divided by a selected divider in normal time-based operation. Generate repeating output edges without toggling each edge in Python. Watchdog A separate countdown that software periodically reloads. Reset when expected software progress stops.
Bit width determines a counter’s numerical range; the tick period converts that range into time. An unsigned n-bit counter has 2ⁿ states. A counter that runs from zero through TOP has TOP + 1 states per cycle. Prescaling lengthens the tick but reduces timing granularity. Always identify the actual peripheral and clock path before applying a formula.
Timer wraparound and alarm scheduling Worked calculation: low-word repeat interval Ttick duration of one timer tick (s) Twrap counter repeat interval (s) n counter or address width (bits) Twrap = 2n × Ttick
Given r_low-word width
n counter or address width (bits) n = 32
and one timer tick = 1 μs.
Number of states = 2^
. Multiply by 1 μs per state:
Twrap counter repeat interval (s) Twrap = 4,294,967,296
μs.
Convert to seconds: 4,294,967,296 ÷ 1,000,000 = 4294.967296 s. Convert to minutes: 4294.967296 ÷ 60 ≈ 71.58 min. Only the low 32-bit word repeats here; the full 64-bit timer continues counting. Atarget target timer count Ntick number of timer ticks rlow measured ADC reading at the low calibration endpoint Anow current timer count mod integer remainder after division 32-bit alarm Atarget = (Anow rlow word + Ntick ) mod 232
Worked calculation: scheduling across a low-word wrap Atarget target timer count Anow current timer count delay requested delay in the stated time/count unit mod integer remainder after division Atarget = (Anow + delay) mod 232
Given
Anow current timer count Anow = 0xFFFFFFF0 = 4,294,967,280
and
delay requested delay in the stated time/count unit delay = 64
μs = 64
Add before applying the width limit: 4,294,967,280 +
64 = 4,294,967,344 = 0x100000030
Reduce modulo 2^32: 4,294,967,344 −
4,294,967,296 = 48 = 0x00000030
Check elapsed ticks: 16 ticks reach zero, then 48 more reach the target; 16 + 48 = 64 ticks. The wrapped target is still in the intended future interval. This is different from programming a target already passed. Monotonic application time is not the raw alarm-register word. Practice set — Counter wraparound and alarm scheduling Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Hypothetical counter repeat time A hypothetical 16-bit counter ticks every 1 μs. Find its wrap interval in ms.
Ttick duration of one timer tick (s) Twrap counter repeat interval (s) n counter or address width (bits) Twrap = 2n × Ttick
Reveal step-by-step solution Identify values and convert units. Ttick duration of one timer tick (s) n counter or address width (bits) n = 16 Ttick = 1 μs
Write the equation. Ttick duration of one timer tick (s) Twrap counter repeat interval (s) n counter or address width (bits) Twrap = 2n × Ttick
Substitute and calculate. Twrap counter repeat interval (s) Twrap = 65,536 × 1 μs = 65,536 μs = 65.536 ms
State the answer and check its meaning. Wrap interval = 65.536 ms. This hypothetical width is not RP2040’s system-timer width.
Practice 2 — Wrapped alarm target Current low word = 0xFFFFFFFC; schedule a 12 μs delay. Find the 32-bit target.
Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Atarget = (Anow + Ntick ) mod 232
Reveal step-by-step solution Identify values and convert units. Anow current timer count delay requested delay in the stated time/count unit Anow = 4,294,967,292 delay = 12
Write the equation. Atarget target timer count Ntick number of timer ticks Anow current timer count mod integer remainder after division Atarget = (Anow + Ntick ) mod 232
Substitute and calculate. Atarget target timer count sum intermediate timer-count sum sum = 4,294,967,304 subtract 4,294,967,296 → Atarget = 8 = 0x00000008
State the answer and check its meaning. Target = 0x00000008; four ticks reach zero, then eight more reach the target.
Practice 3 — Elapsed ticks across wrap A low-word reading changes from 0xFFFFFFF8 to 0x00000018 across one wrap. Find elapsed μs.
elapsedticks elapsed timer ticks start initial timer count mod integer remainder after division end final timer count elapsedticks = (end − start) mod 232
Reveal step-by-step solution Identify values and convert units. start initial timer count end final timer count start = 4,294,967,288 end = 24 tick = 1 μs
Write the equation. elapsedticks elapsed timer ticks start initial timer count mod integer remainder after division end final timer count elapsedticks = (end − start) mod 232
Substitute and calculate. elapsedticks elapsed timer ticks mod integer remainder after division elapsedticks = (24 − 4,294,967,288) mod 4,294,967,296 = 32
State the answer and check its meaning. Elapsed time = 32 μs, assuming no additional complete wraps occurred.
Practice 4 — Minimum hypothetical width At 1 μs per tick, find the minimum hypothetical counter width whose wrap interval is strictly longer than 10 s.
Ttick duration of one timer tick (s) floor round downward to an integer delay requested delay in the stated time/count unit nmin minimum counter width (bits) log₂ base-two logarithm nmin = floor(log₂(delay ÷ Ttick )) + 1
Reveal step-by-step solution Identify values and convert units. Ttick duration of one timer tick (s) delay requested delay in the stated time/count unit delay ÷ Ttick = 10 ÷ 0.000001 = 10,000,000
Write the equation. Ttick duration of one timer tick (s) floor round downward to an integer delay requested delay in the stated time/count unit nmin minimum counter width (bits) log₂ base-two logarithm nmin = floor(log₂(delay ÷ Ttick )) + 1
Substitute and calculate. State the answer and check its meaning. 24 bits gives 16.777216 s. This is a sizing exercise; RP2040’s hardware timer widths are fixed.
PWM limits: validate the divider and counter together The PWM divider has an integer part and four fractional bits, so fractional increments are 1/16. For ordinary time-based examples, use an effective divider from 1 to 255 + 15/16. Normal edge-aligned TOP is 0–65,535. TOP = 0 is a one-count constant-output case; TOP ≥ 1 gives at least two counter counts for a changing waveform. Finite divider and TOP choices can make the actual frequency differ from a target.
Worked limit check — why divider 1 cannot produce this 1 kHz example Step-by-step divider and TOP limit check Ttick duration of one timer tick (s) fsys system-clock frequency (Hz) TOP PWM counter upper limit (count) f frequency (Hz, cycles per second) D PWM clock-divider setting (dimensionless; not duty percentage) C counter counts per PWM period C = fsys ÷ (D × f) TOP = C − 1 Ttick = D ÷ fsys
Given
fsys system-clock frequency (Hz) fsys = 125,000,000 Hz
and
f frequency (Hz, cycles per second) f = 1000 Hz
. Try divider
first first address D PWM clock-divider setting (dimensionless; not duty percentage) D = 1 first
C counter counts per PWM period C = 125,000,000 ÷ (1 × 1000) = 125,000
;
TOP PWM counter upper limit (count) TOP = 124,999
Reject this choice: TOP 124,999 exceeds the 16-bit maximum 65,535. Choose
D PWM clock-divider setting (dimensionless; not duty percentage) D = 2
:
C counter counts per PWM period C = 125,000,000 ÷ (2 × 1000) = 62,500
;
TOP PWM counter upper limit (count) TOP = 62,499,
which fits.
One divided tick = 2 ÷
s shaft speed (revolutions/minute, rpm) 125,000,000 = 0.000000016 s = 16 ns
Period = 62,500 × 16
. Check
f frequency (Hz, cycles per second) s shaft speed (revolutions/minute, rpm) f = 1 ÷ 0.001 s = 1000 Hz
Worked rounding check — a 3 kHz request Step-by-step integer rounding and frequency error frequest requested frequency (Hz) factual realized frequency (Hz) Cchosen selected integer period count Cideal ideal real-valued period count fsys system-clock frequency (Hz) error signed frequency difference (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) Cideal = fsys ÷ (D × frequest ) factual = fsys ÷ (D × Cchosen ) error = factual − frequest
Given
fsys system-clock frequency (Hz) fsys = 125,000,000 Hz
,
D PWM clock-divider setting (dimensionless; not duty percentage) D = 1
and
frequest requested frequency (Hz) frequest = 3000 Hz
Cideal ideal real-valued period count Cideal = 125,000,000 ÷ 3000 = 41,666.666
… counts, which is not an integer.
Choose the nearby integer
Cchosen selected integer period count Cchosen = 41,667
.
TOP PWM counter upper limit (count) TOP = 41,667 − 1 = 41,666
Check that TOP fits 16 bits.
Recalculate
factual realized frequency (Hz) factual = 125,000,000 ÷ 41,667 ≈ 2999.976 Hz
Error = 2999.976 −
, so the chosen frequency is slightly lower. This illustrates a possible hardware setting, not a promise that pwmio selects this pair.
Practice set — PWM limits and rounding Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Minimum realizable divider For 500 Hz PWM at 125 MHz, find the smallest divider in 1/16 steps that allows no more than 65,536 period counts.
Dchosen selected divider on the supported hardware grid fsys system-clock frequency (Hz) Dmin minimum divider before hardware-grid rounding ceil round upward to an integer f frequency (Hz, cycles per second) Dmin = fsys ÷ (65,536 × f) Dchosen = ceil(16 × Dmin ) ÷ 16
Reveal step-by-step solution Identify values and convert units. fsys system-clock frequency (Hz) f frequency (Hz, cycles per second) fsys = 125,000,000 Hz f = 500 Hz
Write the equation. Dchosen selected divider on the supported hardware grid fsys system-clock frequency (Hz) Dmin minimum divider before hardware-grid rounding ceil round upward to an integer f frequency (Hz, cycles per second) Dmin = fsys ÷ (65,536 × f) Dchosen = ceil(16 × Dmin ) ÷ 16
Substitute and calculate. Dmin minimum divider before hardware-grid rounding ceil round upward to an integer Dmin = 3.814697265625 ceil(16 × Dmin ) ÷ 16 = 62 ÷ 16 = 3.875
State the answer and check its meaning. Smallest grid divider = 3.875; ideal period counts ≈ 64,516.129, within the limit.
Practice 2 — Integer period choice For 7 kHz PWM at 125 MHz and divider 1, choose nearest integer period counts and find TOP.
frequest requested frequency (Hz) Cchosen selected integer period count fsys system-clock frequency (Hz) round round to the nearest integer TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) Cchosen = round(fsys ÷ (D × frequest )) TOP = Cchosen − 1
Reveal step-by-step solution Identify values and convert units. frequest requested frequency (Hz) fsys system-clock frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) fsys = 125,000,000 Hz D = 1 frequest = 7000 Hz
Write the equation. frequest requested frequency (Hz) Cchosen selected integer period count fsys system-clock frequency (Hz) round round to the nearest integer TOP PWM counter upper limit (count) D PWM clock-divider setting (dimensionless; not duty percentage) Cchosen = round(fsys ÷ (D × frequest )) TOP = Cchosen − 1
Substitute and calculate. Cchosen selected integer period count Cideal ideal real-valued period count TOP PWM counter upper limit (count) Cideal ≈ 17,857.142857 Cchosen = 17,857 TOP = 17,856
State the answer and check its meaning. 17,857 counts and TOP = 17,856; the counter range is valid.
Practice 3 — Signed frequency error Requested frequency is 7000 Hz; the model produces 7000.056 Hz. Find the signed error.
frequest requested frequency (Hz) factual realized frequency (Hz) Δf signed frequency difference (Hz) Δf = factual − frequest
Reveal step-by-step solution Identify values and convert units. frequest requested frequency (Hz) factual realized frequency (Hz) factual = 7000.056 Hz frequest = 7000 Hz
Write the equation. frequest requested frequency (Hz) factual realized frequency (Hz) Δf signed frequency difference (Hz) Δf = factual − frequest
Substitute and calculate. Δf signed frequency difference (Hz) Δf = 7000.056 − 7000 = +0.056 Hz
State the answer and check its meaning. The actual frequency is approximately 0.056 Hz higher.
Practice 4 — Relative frequency error Requested frequency is 3000 Hz; actual frequency is 2999.976 Hz. Find signed percentage error.
errorpercent relative frequency error (%) frequest requested frequency (Hz) factual realized frequency (Hz) errorpercent = (factual − frequest ) ÷ frequest × 100
Reveal step-by-step solution Identify values and convert units. frequest requested frequency (Hz) factual realized frequency (Hz) factual = 2999.976 Hz frequest = 3000 Hz
Write the equation. errorpercent relative frequency error (%) frequest requested frequency (Hz) factual realized frequency (Hz) errorpercent = (factual − frequest ) ÷ frequest × 100
Substitute and calculate. errorpercent relative frequency error (%) errorpercent = (−0.024 ÷ 3000) × 100 = −0.0008%
State the answer and check its meaning. Approximately −0.0008%; the actual frequency is slightly lower.
Translate pulse width into the CircuitPython duty scale Worked calculation: servo pulse width to API duty round round to the nearest integer TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) p percentage on a 0–100 scale (%) u integer CircuitPython duty setting, from 0 to 65,535 T = 1 ÷ f p = TON ÷ T × 100 u ≈ round(TON ÷ T × 65,535)
Given frame frequency
f frequency (Hz, cycles per second) f = 50 Hz
.
T period of one cycle (s unless another time unit is stated) s shaft speed (revolutions/minute, rpm) T = 1 ÷ 50 = 0.020 s = 20 ms
For 1.0 ms,
ratio dimensionless pulse-width fraction ratio = 1.0 ÷ 20 = 0.05
; duty = 5%; API
round round to the nearest integer value CircuitPython ADC API reading value ≈ round(0.05 × 65,535) = 3277
For 1.5 ms,
ratio dimensionless pulse-width fraction ratio = 1.5 ÷ 20 = 0.075
; duty = 7.5%; API
round round to the nearest integer value CircuitPython ADC API reading value ≈ round(4915.125) = 4915
For 2.0 ms,
ratio dimensionless pulse-width fraction ratio = 2.0 ÷ 20 = 0.10
; duty = 10%; API
round round to the nearest integer value CircuitPython ADC API reading value ≈ round(6553.5) = 6554
Use the same units for pulse and period. These are 16-bit API values, not direct compare-register counts; servo calibration still determines the resulting position. These are illustrative servo pulse widths. The actual servo’s calibration determines its angle limits. A 16-bit API duty value is not a direct TOP or compare-register value. Lower TOP reduces the number of distinct realizable pulse widths, even though the API still accepts values across 0–65,535.
Practice set — Servo pulse width and API duty Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Servo frame period Find the period of a 50 Hz servo frame in ms.
T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) T = 1 ÷ f
Reveal step-by-step solution Identify values and convert units. f frequency (Hz, cycles per second) f = 50 Hz
Write the equation. T period of one cycle (s unless another time unit is stated) f frequency (Hz, cycles per second) T = 1 ÷ f
Substitute and calculate. T period of one cycle (s unless another time unit is stated) s shaft speed (revolutions/minute, rpm) T = 1 ÷ 50 = 0.020 s = 20 ms
State the answer and check its meaning. Frame period = 20 ms.
Practice 2 — API value for a pulse For a 1.2 ms HIGH pulse in a 20 ms frame, estimate the integer CircuitPython duty_cycle.
round round to the nearest integer TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) u integer CircuitPython duty setting, from 0 to 65,535 u ≈ round(TON ÷ T × 65,535)
Reveal step-by-step solution Identify values and convert units. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) TON = 1.2 ms T = 20 ms
Write the equation. round round to the nearest integer TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) u integer CircuitPython duty setting, from 0 to 65,535 u ≈ round(TON ÷ T × 65,535)
Substitute and calculate. round round to the nearest integer ratio dimensionless pulse-width fraction ratio = 0.06 0.06 × 65,535 = 3932.1 round → 3932
State the answer and check its meaning. API duty_cycle ≈ 3932; servo angle still depends on calibration.
Practice 3 — Pulse from an API value For duty_cycle = 4915 and a 20 ms period, estimate HIGH time in ms.
TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) u integer CircuitPython duty setting, from 0 to 65,535 TON ≈ u ÷ 65,535 × T
Reveal step-by-step solution Identify values and convert units. T period of one cycle (s unless another time unit is stated) u integer CircuitPython duty setting, from 0 to 65,535 u = 4915 T = 20 ms
Write the equation. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) u integer CircuitPython duty setting, from 0 to 65,535 TON ≈ u ÷ 65,535 × T
Substitute and calculate. TON HIGH time within one period (same time unit as T) TON ≈ 4915 ÷ 65,535 × 20 ≈ 1.49996 ms
State the answer and check its meaning. Approximately 1.5 ms; integer API scaling introduces a small difference.
Practice 4 — LOW interval A 20 ms frame contains a 1.8 ms HIGH pulse. Find its LOW interval.
TOFF LOW time within one period (same time unit as T) TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) TOFF = T − TON
Reveal step-by-step solution Identify values and convert units. TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) T = 20 ms TON = 1.8 ms
Write the equation. TOFF LOW time within one period (same time unit as T) TON HIGH time within one period (same time unit as T) T period of one cycle (s unless another time unit is stated) TOFF = T − TON
Substitute and calculate. TOFF LOW time within one period (same time unit as T) TOFF = 20 − 1.8 = 18.2 ms
State the answer and check its meaning. LOW interval = 18.2 ms; HIGH + LOW equals the frame period.
Watchdog operation: feed only after useful progress RP2040 · Watchdog RESET Useful progress keeps the watchdog fed The temperature-control task is an application example, not an RP2040 hardware block. The watchdog recovery path uses RP2040’s hardware and CircuitPython RESET mode. Either heater state may feed the watchdog after input and output checks succeed.
Healthy cycle Valid input and successful output Invalid sensor data Loop continues without feeding Output check fails Input is valid; progress is incomplete Application stalls Time advances while code is stuck
T below threshold → heater ON T at/above threshold → heater OFF
Time since model start 0 ms
Feeds completed 0
Start / restart model Advance simulation Reset explorer
Figure 5.17. RP2040 watchdog application flow: validate useful work, feed on successful cycles, and allow timeout recovery when progress stops. This replaces the generic source flow with an explicit application/hardware distinction. Original general diagram (slide 88) · RP2040 watchdog reference: Section 4.7 · CircuitPython watchdog API A watchdog counts down independently of the application’s intended loop flow. Healthy software reloads it before expiry. If the program becomes stuck and stops reloading it, expiry can reset the controller. Feeding at the top of every loop without checking useful work can hide faults: an application may continue looping while never obtaining valid sensor data.
Worked calculation: watchdog loop time and margin Ttimeout watchdog timeout tdisplay display update duration (s) tsensor sensor operation duration (s) tdelay program delay (s) Tloop loop duration M available time margin Tloop = tsensor + tdisplay + tdelay M = Ttimeout − Tloop
Given sensor work = 0.12 s, display work = 0.08 s and loop
delay requested delay in the stated time/count unit delay = 0.20 s
Add the work:
Tloop loop duration s shaft speed (revolutions/minute, rpm) Tloop = 0.12 + 0.08 + 0.20 = 0.40 s = 400 ms
For the illustrative
Ttimeout watchdog timeout Ttimeout = 2.0 s
,
M available time margin M = 2.0 − 0.40 = 1.60 s
Ratio = 2.0 ÷
nominal loop durations. This does not prove the worst-case workload will fit; measure legitimate blocking/communication delays and leave suitable M.
A blocking call longer than the watchdog timeout can still cause a reset. Feed after validated useful work. import time
import microcontroller
from watchdog import WatchDogMode
# Teaching pattern: replace the console work with a validated I/O cycle.
w = microcontroller.watchdog
w.timeout = 2.0
w.mode = WatchDogMode.RESET
try:
while True:
print("Completed one demonstration cycle")
w.feed()
time.sleep(0.2)
finally:
w.mode = WatchDogMode.NONEIn this console-only pattern, feed reloads the watchdog after the demonstrated work. For a real application, place it after successful input, processing and required output checks. The Raspberry Pi CircuitPython port supports RESET mode; RAISE is not implemented there, and its timeout limit is 8 s in the checked implementation. NONE disables the watchdog in that port. A hardware reset does not execute finally; this cleanup handles normal exit where the runtime reaches it. Check the installed firmware when reproducing the example.
Practice set — Watchdog timing budget Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Nominal loop time Sensor work takes 0.15 s, display work 0.05 s and sleep 0.25 s. Find nominal loop time.
tdisplay display update duration (s) tsensor sensor operation duration (s) Tsleep sleep duration Tloop loop duration Tloop = tsensor + tdisplay + Tsleep
Reveal step-by-step solution Identify values and convert units. tdisplay display update duration (s) tsensor sensor operation duration (s) Tsleep sleep duration tsensor = 0.15 s tdisplay = 0.05 s Tsleep = 0.25 s
Write the equation. tdisplay display update duration (s) tsensor sensor operation duration (s) Tsleep sleep duration Tloop loop duration Tloop = tsensor + tdisplay + Tsleep
Substitute and calculate. Tloop loop duration Tloop = 0.15 + 0.05 + 0.25 = 0.45 s
State the answer and check its meaning. Nominal loop time = 0.45
s shaft speed (revolutions/minute, rpm) s = 450 ms
Practice 2 — Timeout margin A watchdog timeout is 1.5 s and nominal loop time is 0.45 s. Find the nominal margin.
Ttimeout watchdog timeout Tloop loop duration M available time margin M = Ttimeout − Tloop
Reveal step-by-step solution Identify values and convert units. Ttimeout watchdog timeout Tloop loop duration Ttimeout = 1.5 s Tloop = 0.45 s
Write the equation. Ttimeout watchdog timeout Tloop loop duration M available time margin M = Ttimeout − Tloop
Substitute and calculate. M available time margin M = 1.5 − 0.45 = 1.05 s
State the answer and check its meaning. Nominal margin = 1.05 s; measure worst-case time before relying on it.
Practice 3 — Choose timeout from a measured worst case The measured longest valid cycle is 1.1 s. Choose a timeout with 0.4 s additional margin.
t_worst_valid measured worst-case valid loop duration (s) Ttimeout watchdog timeout M available time margin Ttimeout = t_worst_valid + M
Reveal step-by-step solution Identify values and convert units. t_worst_valid measured worst-case valid loop duration (s) M available time margin t_worst_valid = 1.1 s M = 0.4 s
Write the equation. t_worst_valid measured worst-case valid loop duration (s) Ttimeout watchdog timeout M available time margin Ttimeout = t_worst_valid + M
Substitute and calculate. Ttimeout watchdog timeout Ttimeout = 1.1 + 0.4 = 1.5 s
State the answer and check its meaning. Illustrative timeout = 1.5 s; feed after validated progress and allow for unmeasured delays.
Practice 4 — Blocking-time upper bound Between feeds, a 2 s timeout includes 0.12 s of other work and 0.20 s sleep. Find the strict upper bound for an additional blocking call.
Equation to use: t_block < timeout − t_other − t_sleep
Reveal step-by-step solution Identify values and convert units. Ttimeout watchdog timeout Tsleep sleep duration tother time spent on other valid operations (s) Ttimeout = 2.0 s tother = 0.12 s Tsleep = 0.20 s
Write the equation. t_block < timeout − t_other − t_sleep
Substitute and calculate. Ttimeout watchdog timeout Tsleep sleep duration tother time spent on other valid operations (s) Ttimeout − tother − Tsleep = 2.0 − 0.12 − 0.20 = 1.68 s
State the answer and check its meaning. The call must be shorter than 1.68 s even in this simplified budget; leave further margin. Equality is not safe.
Software timing: measure elapsed time without accumulating sleep drift Worked calculation: a 200 ms software schedule periodns schedule period in nanoseconds periodms schedule period in milliseconds periods schedule period in seconds ftask task executions per second periodns = periodms × 106 ftask = 1 ÷ periods
Given A_target period = 200 ms. Convert to seconds: 200 ÷
Convert to nanoseconds:
periodns schedule period in nanoseconds periodns = 200 × 1,000,000 = 200,000,000 ns
, matching the code below.
Nominal task rate = 1 ÷
executions/s.
The polling sleep is 0.001 s = 1 ms. Runtime work and polling add jitter; nanosecond units do not guarantee nanosecond accuracy. import time
period_ns = 200_000_000 # 200 ms
next_due = time.monotonic_ns() + period_ns
while True:
now = time.monotonic_ns()
if now >= next_due:
print("Periodic task")
next_due += period_ns
if next_due <= now:
next_due = now + period_ns # skip missed slots
time.sleep(0.001)This schedules a periodic console task against a monotonic clock rather than adding work time to a fixed sleep every cycle. It remains software polling, with runtime and scheduling jitter; it is not a hardware interrupt or a precision waveform generator. The nanosecond unit of monotonic_ns does not promise nanosecond hardware resolution. PWM hardware is the appropriate tool for repeated output pulse edges.
Practice set — Software scheduling Four practices, four equations. Write your working first, then reveal each solution.
Practice 1 — Nanosecond period Convert a 125 ms scheduling period to nanoseconds.
periodns schedule period in nanoseconds periodms schedule period in milliseconds periodns = periodms × 106
Reveal step-by-step solution Identify values and convert units. periodms schedule period in milliseconds periodms = 125 1 ms = 1,000,000 ns
Write the equation. periodns schedule period in nanoseconds periodms schedule period in milliseconds periodns = periodms × 106
Substitute and calculate. periodns schedule period in nanoseconds periodns = 125 × 1,000,000 = 125,000,000 ns
State the answer and check its meaning. Use 125,000,000 ns as the nominal period; unit precision is not timing accuracy.
Practice 2 — Nominal task rate For a 0.125 s period, find the nominal executions per second.
periods schedule period in seconds ftask task executions per second ftask = 1 ÷ periods
Reveal step-by-step solution Identify values and convert units. periods schedule period in seconds periods = 0.125 s
Write the equation. periods schedule period in seconds ftask task executions per second ftask = 1 ÷ periods
Substitute and calculate. ftask task executions per second ftask = 1 ÷ 0.125 = 8 executions/s
State the answer and check its meaning. Nominal rate = 8 executions/s; runtime and polling can introduce jitter.
Practice 3 — Next fixed deadline The previous scheduled deadline is 1,000,000,000 ns and the period is 125,000,000 ns. Find the next deadline without adding work time.
previousdue previous scheduled timestamp (ns) periodns schedule period in nanoseconds nextdue next scheduled timestamp (ns) nextdue = previousdue + periodns
Reveal step-by-step solution Identify values and convert units. previousdue previous scheduled timestamp (ns) periodns schedule period in nanoseconds previousdue = 1,000,000,000 ns periodns = 125,000,000 ns
Write the equation. previousdue previous scheduled timestamp (ns) periodns schedule period in nanoseconds nextdue next scheduled timestamp (ns) nextdue = previousdue + periodns
Substitute and calculate. nextdue next scheduled timestamp (ns) nextdue = 1,000,000,000 + 125,000,000 = 1,125,000,000 ns
State the answer and check its meaning. Next scheduled deadline = 1,125,000,000 ns.
Practice 4 — Task lateness A task runs at
now current timestamp (ns) now = 1,130,000,000 ns
with
deadline scheduled timestamp (ns) deadline = 1,125,000,000 ns
Find its lateness in ms.
latenessns lateness in nanoseconds deadline scheduled timestamp (ns) max choose the largest argument now current timestamp (ns) latenessns = max(0, now − deadline)
Reveal step-by-step solution Identify values and convert units. deadline scheduled timestamp (ns) now current timestamp (ns) now = 1,130,000,000 ns deadline = 1,125,000,000 ns
Write the equation. latenessns lateness in nanoseconds deadline scheduled timestamp (ns) max choose the largest argument now current timestamp (ns) latenessns = max(0, now − deadline)
Substitute and calculate. latenessns lateness in nanoseconds latenessms lateness in milliseconds latenessns = 5,000,000 ns latenessms = 5,000,000 ÷ 1,000,000 = 5
State the answer and check its meaning. The task is 5 ms late. This measures software lateness, not a hardware PWM edge error.
Calculation tutorial — timer, PWM and watchdog Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Ntick number of timer ticks t elapsed time or duration (s unless otherwise stated) ftick timer tick rate (ticks/s) fsys system-clock frequency (Hz) D PWM clock-divider setting (dimensionless; not duty percentage) C counter counts per PWM period TOP PWM counter upper limit (count) Ttimeout watchdog timeout Tloop loop duration M available time margin Example 1 — Find the timer ticks for 250 ms given a tick rate of 1,000,000 ticks/s Given: Tick rate 1,000,000 ticks/s; delay 0.250 s.
Ntick = t × ftick Ntick = 0.250 s × 1,000,000 ticks/s Ntick = 250,000
Interpretation: At this tick rate each tick is one microsecond.
Example 2 — Find TOP for 20 kHz edge-aligned PWM given a 125 MHz system clock and divider 1 Given: System clock 125 MHz; divider 1; edge-aligned PWM.
C = fsys ÷ (D × 20,000 Hz) C = 125,000,000 Hz ÷ (1 × 20,000 Hz) C = 6250 TOP = C − 1 TOP = 6249
Interpretation: The result is within the 16-bit counter range. CircuitPython selects hardware settings internally.
Example 3 — Find the watchdog time margin given a 1.5 s timeout and a 0.45 s valid loop Given: Timeout 1.5 s; valid loop takes 0.45 s.
M = Ttimeout − Tloop M = 1.5 s − 0.45 s M = 1.05 s
Interpretation: Use a measured worst-case valid loop duration before relying on this margin.
CHAPTER 5 / SUBTOPIC 5.3.3
5.3.3 Operation of the RP2040-based embedded system Chapter lesson RP2040 hardware reference · CircuitPython application
This section builds a reusable model for understanding RP2040-based embedded systems and solving the associated test calculations.
Key terms — definitions first Boot sequence The ordered hardware/software steps that occur after reset before the user application runs. CircuitPython runtime The interpreter and board support that expose Python modules and hardware objects. Main loop A repeated sequence that reads inputs, processes values and updates outputs. Watchdog A timer-based recovery mechanism that can reset a system if expected software progress stops. Latency The time between an event occurring and the system responding. Use this flow to trace a real system: power/reset → boot support → CircuitPython runtime → code.py initialization → repeated input/process/output control. On the EDU PICO, the selected board pin and actual module wiring determine how software objects connect to physical components.
Reset & boot ROM / flash CircuitPython runtime + libraries Initialize pins / objects Read sensor / button Process scale / decide Update output display / actuator Figure 5.18. Startup and input–process–output flow. The first three blocks happen during startup; the read–process–update cycle repeats while the application runs.Timing a sampled control loop If a loop performs processing and then waits, its period is approximately Tloop = Twork + Tsleep. Therefore loop rate ≈ 1/Tloop. A software wait is not a substitute for a hardware PWM or timer when precise edge timing is required.
Worked calculation: sample rate and loop timing A 20 ms sample interval corresponds to 1/0.020 = 50 samples/s .
If processing takes 4 ms and the program then sleeps 16 ms, loop period ≈ 4+
; ideal rate = 50 loops/s.
If processing time rises to 7 ms but sleep remains 16 ms, period ≈ 23 ms; rate ≈ 43.5 loops/s.
A watchdog is a recovery tool, not a precision timer. A program periodically services it while healthy; if execution becomes stuck and the watchdog is not serviced, the chip can reset. Choose a timeout longer than legitimate blocking operations and use a recovery strategy appropriate to the application.
Practice 5.3.3 — try before revealing the solution A program samples every 50 ms. Find sample rate.
A control loop needs 3 ms processing and a 17 ms sleep. Find the ideal loop rate.
Give one reason actual timing may vary.
Worked answer: 50 ms = 0.05 s, so 20 samples/s. 3+17=20 ms, so 50 loops/s. Processing variation, interrupts, I/O wait or runtime overhead can change the interval.
Boot, firmware and application: three different instruction levels After reset, on-chip boot ROM performs startup support and attempts the supported boot path. In normal flash boot, a second-stage bootloader configures flash access and transfers control to the firmware. CircuitPython initializes its runtime and board support, processes startup files where applicable, and executes code.py. The processor always executes machine instructions, including the instructions implementing the interpreter; it does not directly decode Python text as CPU opcodes.
Follow one complete potentiometer-to-pixel cycle import time
import board
import analogio
import neopixel
with analogio.AnalogIn(board.GP28) as pot:
pixels = neopixel.NeoPixel(
board.GP14, 5, brightness=0.1, auto_write=False,
pixel_order=neopixel.GRB,
)
try:
while True:
reading = pot.value
level_percent = reading * 100.0 / 65535
colour = (0, 255, 0) if level_percent >= 50.0 else (255, 0, 0)
pixels.fill((0, 0, 0))
pixels[0] = colour
pixels.show()
time.sleep(0.02)
finally:
pixels.fill((0, 0, 0))
pixels.show()
pixels.deinit()Program action Hardware/software interpretation Read pot.value ADC samples GP28; the driver returns a scaled integer. Calculate level_percent The runtime performs arithmetic and stores the result in working memory. Compare against 50% The interpreted decision selects a colour; several machine operations may implement it. Update pixels[0] Change the software pixel buffer; auto_write=False delays transmission. Call pixels.show() The library transmits pixel data through GP14; the LEDs then display it. Wait 20 ms Pause application progress; hardware timing and peripherals have their own behaviour.
The two readings 32759 and 32776 lie on different sides of the 50% threshold, although a display rounded to one decimal place may show both as 50.0%. This is a software decision about the stored numeric value, not a fault in the CPU or OLED. Change the input after a read and the program still uses the captured value until the next sample.
Diagnose a system by following information and power Observed symptom Questions to investigate No application output after reset Did firmware boot, did code.py load, and did initialization raise an exception? A reading stays fixed Is the correct pin/interface selected? Is the signal changing? Does a new conversion complete? The buffer changes but LEDs do not Was show called? Is the correct signal pin selected? Are power and ground correct? A motor command is present but the shaft is stopped Check the driver, motor supply, terminals, load and physical connections. Repeated resets Distinguish watchdog expiry, power problems and explicit reset requests; inspect the preceding workload. Timing is slower than predicted Include runtime work, conversion waits, transfer overhead and the sleep interval.
Integrated calculation — estimate a complete monitoring cycle Suppose sensor conversion takes 80 ms, a six-byte I²C read at 100 kHz needs one address byte plus six data bytes, processing takes 3 ms, and sleep is 20 ms. Seven bytes × 9 clocks = 63 clocks = 0.63 ms of clocked transfer. Total lower-bound cycle ≈ 80 + 0.63 + 3 + 20 = 103.63 ms, giving about 9.65 cycles/s. Add command transfers, START/STOP timing, display work and runtime overhead for a complete measured estimate.
Picture and technical references for this chapter The general architecture pictures are extracted from the supplied Word document. Their captions identify source slide numbers. Device-specific facts and calculations follow the RP2040 datasheet; CircuitPython examples follow the relevant API and port implementation. Picture pixels retain the language of the source.
Calculation tutorial — complete loop timing Identify the given values, write the formula, substitute with consistent units, then interpret the answer.
Tloop loop duration Twork processing duration Tsleep sleep duration fs sampling frequency (samples/s) Example 1 — Find loop period and sample rate given 4 ms of work followed by 16 ms of sleep Given: Work 4 ms; sleep 16 ms.
Tloop = Twork + Tsleep Tloop = 4 ms + 16 ms Tloop = 20 ms fs = 1 ÷ Tloop fs = 1 ÷ 0.020 s fs = 50 samples/s
Interpretation: This is an ideal loop rate. Processing variation causes timing variation.
Example 2 — Find loop period and sample rate given 8 ms of work followed by 16 ms of sleep Given: Work 8 ms; unchanged sleep of 16 ms.
Tloop = 8 ms + 16 ms Tloop = 24 ms fs = 1 ÷ 0.024 s fs ≈ 41.67 samples/s
Interpretation: Keeping the sleep unchanged does not keep the whole loop period unchanged.
Hardware Module 01: Push buttons
Learning goal Read the active-low A and B buttons and report state changes.
What the device does
A push button is a digital input device . Pressing it closes a contact so the controller can detect a user command. EDU PICO buttons A and B are active-low: an unpressed button reads True, while a pressed button reads False.
Buttons on EDU PICO The yellow A and blue B buttons are located at the lower-right edge of the board. Select the picture to enlarge it.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 28–32.
Interfacing connection
Button signal EDU PICO connection CircuitPython pin Meaning Button A output Onboard button A GP0 Digital input with internal pull-up Button B output Onboard button B GP1 Digital input with internal pull-up OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Displays the button states
How the program uses it The loop detects state changes and reports each button as PRESSED or released without repeatedly redrawing unchanged values.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 01; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 01: read the active-low A and B buttons on GP0 and GP1."""
import time
import board
import busio
import digitalio
import adafruit_ssd1306
def make_button(pin):
button = digitalio.DigitalInOut(pin)
button.switch_to_input(pull=digitalio.Pull.UP)
return button
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
button_a = make_button(board.GP0)
button_b = make_button(board.GP1)
last_state = None
try:
while True:
state = (not button_a.value, not button_b.value)
if state != last_state:
label_a = "PRESSED" if state[0] else "released"
label_b = "PRESSED" if state[1] else "released"
oled.fill(0)
oled.text('(1) Buttons', 0, 0, 1)
oled.text('A GP0: ' + label_a, 0, 16, 1)
oled.text('B GP1: ' + label_b, 0, 28, 1)
oled.text('Active-low inputs', 0, 40, 1)
oled.show()
print("Button A:", label_a, "Button B:", label_b)
last_state = state
time.sleep(0.02)
finally:
button_a.deinit()
button_b.deinit()
i2c.deinit()
Open 01_push_buttons.py
Hardware Module 02: AHT20 temperature and humidity
Learning goal Read environmental measurements from an I2C sensor.
What the device does The AHT20 is a digital environmental sensor . It measures air temperature in degrees Celsius and relative humidity as a percentage, then sends calibrated readings over I2C.
AHT20 on EDU PICO The temperature/humidity module is beside the RGB LEDs and shares the I2C bus with the OLED and APDS9960.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 156–159.
Interfacing connection AHT20 signal EDU PICO Grove/board port CircuitPython pin Sensor output SDA I2C Grove/onboard I2C GP4 Bidirectional measurement data SCL I2C Grove/onboard I2C GP5 I2C clock VCC/GND I2C port power 3V3/GND Sensor power and reference
How the program uses it The program samples temperature and relative humidity every two seconds and sends the results to both the OLED and Thonny Shell.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 03; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 03: read the AHT20 temperature and humidity sensor over I2C."""
import time
import board
import busio
import adafruit_ahtx0
import adafruit_ssd1306
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = adafruit_ahtx0.AHTx0(i2c)
try:
while True:
temperature = sensor.temperature
humidity = sensor.relative_humidity
oled.fill(0)
oled.text('(3) AHT20', 0, 0, 1)
oled.text('SDA GP4 / SCL GP5', 0, 16, 1)
oled.text('Temp: {:.2f} C'.format(temperature), 0, 28, 1)
oled.text('Humidity: {:.2f}%'.format(humidity), 0, 40, 1)
oled.show()
print("Temperature: {:.2f} C, Humidity: {:.2f}%".format(
temperature, humidity
))
time.sleep(2)
finally:
i2c.deinit()
Open 03_temperature_humidity_aht20.py
Hardware Module 03: APDS9960 proximity
Learning goal Measure reflected infrared proximity values.
What the device does The APDS9960 is an optical sensor . In proximity mode it emits infrared light and measures the reflection to estimate whether an object is close to the sensor.
APDS9960 on EDU PICO One physical sensor provides proximity, light, gesture, and colour modes. This lesson enables only proximity mode.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 91–94.
Interfacing connection Sensor signal EDU PICO Grove/board port CircuitPython pin Sensor output SDA I2C Grove/onboard I2C GP4 8-bit proximity value SCL I2C Grove/onboard I2C GP5 I2C clock VCC/GND I2C port power 3V3/GND Sensor power and reference
How the program uses it The program enables proximity mode, repeatedly reads the proximity property, displays it, and disables the sensor safely during cleanup.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 04; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 04: read proximity from the APDS9960 sensor."""
import time
from adafruit_apds9960.apds9960 import APDS9960
import board
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = APDS9960(i2c)
sensor.enable_proximity = True
try:
while True:
proximity = sensor.proximity
show_module(oled, 4, "APDS9960", (
"Mode: Proximity",
"SDA GP4 / SCL GP5",
"Value: {}".format(proximity),
))
print("Proximity:", proximity)
time.sleep(0.8)
finally:
sensor.enable_proximity = False
i2c.deinit()
Open 04_apds9960_proximity.py
Hardware Module 04: APDS9960 light
Learning goal Calculate lux and colour temperature from RGBC measurements.
What the device does In ambient-light mode, the APDS9960 acts as a digital light sensor . Its red, green, blue, and clear photodiodes allow software to estimate illuminance and colour temperature.
APDS9960 light mode This is the same four-function optical sensor used by proximity, gesture, and colour lessons; software selects the required mode.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 153–155.
Interfacing connection Sensor signal EDU PICO Grove/board port CircuitPython pin Sensor output SDA I2C Grove/onboard I2C GP4 RGBC data, lux, and colour temperature SCL I2C Grove/onboard I2C GP5 I2C clock VCC/GND I2C port power 3V3/GND Sensor power and reference
How the program uses it The program waits for valid RGBC data and calculates lux and colour temperature. Dark or degenerate RGB readings display an unavailable colour temperature rather than stopping with a division-by-zero error.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 05; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 05: calculate illuminance and colour temperature with APDS9960."""
import time
from adafruit_apds9960.apds9960 import APDS9960
from adafruit_apds9960 import colorutility
import board
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = APDS9960(i2c)
sensor.enable_color = True
try:
while True:
while not sensor.color_data_ready:
time.sleep(0.005)
red, green, blue, clear = sensor.color_data
lux = colorutility.calculate_lux(red, green, blue)
try:
colour_temp = colorutility.calculate_color_temperature(red, green, blue)
temperature_text = '{:.2f} K'.format(colour_temp)
except ZeroDivisionError:
# Dark or degenerate RGB readings cannot define a colour temperature.
temperature_text = 'unavailable'
show_module(oled, 5, "APDS9960 Light", (
"Lux: {:.2f}".format(lux),
"Temp: " + temperature_text,
"Clear: {}".format(clear),
))
print("Lux: {:.2f}, colour temperature: {}".format(
lux, temperature_text
))
time.sleep(1)
finally:
sensor.enable_color = False
i2c.deinit()
Open 05_apds9960_light.py
Hardware Module 05: APDS9960 gesture
Learning goal Recognise up, down, left, and right hand gestures.
What the device does In gesture mode, the APDS9960 is a contactless motion sensor . Four directional photodiodes compare reflected infrared energy to identify hand movement such as up, down, left, and right.
APDS9960 gesture mode Move a hand a short distance above the optical opening; avoid touching or covering it while a gesture is being read.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 46–53.
Interfacing connection Sensor signal EDU PICO Grove/board port CircuitPython pin Sensor output SDA I2C Grove/onboard I2C GP4 Numeric gesture code SCL I2C Grove/onboard I2C GP5 I2C clock VCC/GND I2C port power 3V3/GND Sensor power and reference
How the program uses it The program maps each numeric gesture code to a readable direction and shows detected movements on the OLED and Shell.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 06; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 06: recognise up, down, left, and right APDS9960 gestures."""
import time
from adafruit_apds9960.apds9960 import APDS9960
import board
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
GESTURES = {1: "Up", 2: "Down", 3: "Left", 4: "Right"}
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = APDS9960(i2c)
sensor.enable_proximity = True
sensor.enable_gesture = True
current = "Move hand"
try:
while True:
gesture = sensor.gesture()
if gesture in GESTURES:
current = GESTURES[gesture]
print("Gesture:", current)
show_module(oled, 6, "APDS9960", (
"Mode: Gesture",
"Up Down Left Right",
"Gesture: " + current,
))
time.sleep(0.05)
finally:
sensor.enable_gesture = False
sensor.enable_proximity = False
i2c.deinit()
Open 06_apds9960_gesture.py
Hardware Module 06: APDS9960 colour
Learning goal Read the raw red, green, blue, and clear channels.
What the device does In colour mode, the APDS9960 is an optical sensor that measures red, green, blue, and unfiltered clear light. The four values describe the colour and overall brightness of reflected or ambient light.
APDS9960 colour mode Place a coloured surface consistently above the sensor because distance and ambient light affect the RGBC readings.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 73–77.
Interfacing connection Sensor signal EDU PICO Grove/board port CircuitPython pin Sensor output SDA I2C Grove/onboard I2C GP4 Red, green, blue, and clear channels SCL I2C Grove/onboard I2C GP5 I2C clock VCC/GND I2C port power 3V3/GND Sensor power and reference
How the program uses it The program retrieves one RGBC tuple and displays and prints all four related sensor values.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 07; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 07: display raw red, green, blue, and clear APDS9960 values."""
import time
from adafruit_apds9960.apds9960 import APDS9960
import board
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
sensor = APDS9960(i2c)
sensor.enable_color = True
try:
while True:
while not sensor.color_data_ready:
time.sleep(0.005)
red, green, blue, clear = sensor.color_data
show_module(oled, 7, "APDS9960 Colour", (
"Red: {}".format(red),
"Green: {}".format(green),
"Blue: {} C:{}".format(blue, clear),
))
print("R:{} G:{} B:{} C:{}".format(red, green, blue, clear))
time.sleep(1)
finally:
sensor.enable_color = False
i2c.deinit()
Open 07_apds9960_colour.py
Hardware Module 07: PDM microphone
Learning goal Capture digital audio samples and calculate relative sound level.
What the device does The PDM microphone is a digital acoustic sensor . It converts air-pressure variations into a high-rate pulse-density bitstream that software processes into an estimate of sound level.
PDM microphone on EDU PICO Keep the board stable during measurement; vibration and handling can create false sound peaks.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 105–114.
Interfacing connection Microphone signal EDU PICO connection CircuitPython pin Sensor output DATA Onboard PDM microphone GP2 Pulse-density audio samples CLOCK Onboard PDM microphone GP3 Sampling clock generated by Pico OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Displays calculated sound level
How the program uses it The program records microphone samples, removes their mean and calculates RMS magnitude and a relative logarithmic level. This is a relative signal indication, not calibrated sound-pressure level.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 08; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 08: measure the relative sound level of the PDM microphone."""
import array
import math
import time
import board
import audiobusio
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
def calculate_rms(values):
average = sum(values) / len(values)
total = 0.0
for sample in values:
total += (sample - average) * (sample - average)
return math.sqrt(total / len(values))
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
microphone = audiobusio.PDMIn(
board.GP3,
board.GP2,
sample_rate=16000,
bit_depth=16,
)
samples = array.array("H", [0] * 100)
try:
while True:
microphone.record(samples, len(samples))
magnitude = calculate_rms(samples)
relative_db = 20 * math.log(magnitude) / math.log(10) if magnitude else 0
show_module(oled, 8, "PDM Microphone", (
"Clock GP3 / Data GP2",
"Magnitude: {:.1f}".format(magnitude),
"Relative dB: {:.1f}".format(relative_db),
))
print("Magnitude: {:.1f}, relative dB: {:.1f}".format(
magnitude, relative_db
))
time.sleep(0.05)
finally:
microphone.deinit()
i2c.deinit()
Open 08_pdm_microphone.py
Hardware Module 08: Potentiometer
Learning goal Convert the GP28 ADC reading into voltage and percentage.
What the device does A potentiometer is an adjustable analogue input sensor . Turning its shaft moves a wiper along a resistive track and produces a voltage between ground and the supply voltage.
Potentiometer on EDU PICO Rotate the knob through its available travel; the analogue voltage changes continuously rather than producing only ON/OFF states.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 105–108.
Interfacing connection Potentiometer signal EDU PICO Grove/board port CircuitPython pin Sensor output Wiper/SIG Analogue input/onboard potentiometer GP28 / ADC2 0–3.3 V analogue level VCC Port power 3V3 Top of resistive track GND Port ground GND Voltage reference
How the program uses it The program maps the 16-bit ADC reading to voltage and percentage values and updates the OLED.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 09; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 09: read the GP28 potentiometer as ADC, voltage, and percent."""
import time
import board
import analogio
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
potentiometer = analogio.AnalogIn(board.GP28)
try:
while True:
raw = potentiometer.value
voltage = raw * 3.3 / 65535
percent = raw * 100 / 65535
show_module(oled, 9, "Potentiometer", (
"Input: GP28",
"Voltage: {:.2f} V".format(voltage),
"Position: {:.0f}%".format(percent),
))
print("ADC: {}, voltage: {:.2f} V, position: {:.0f}%".format(
raw, voltage, percent
))
time.sleep(0.2)
finally:
potentiometer.deinit()
i2c.deinit()
Open 09_potentiometer.py
Hardware Module 09: SD card storage
Learning goal Mount, write, read, and unmount a FAT-formatted microSD card.
What the device does A microSD card is removable non-volatile storage . It keeps data without power and communicates with the Pico through SPI, making it useful for data logging and configuration files.
MicroSD socket on EDU PICO The socket is labelled with its SPI range. This tutorial extends the booklet’s logging topic by writing to removable microSD storage.Board location: supplied EDU PICO Booklet V2.0, p. 12. The booklet’s pp. 179–183 focus on Pico flash logging.
Interfacing connection SD signal EDU PICO port/socket CircuitPython pin Direction MISO Onboard microSD socket GP16 Card → EDU PICO data CS Onboard microSD socket GP17 EDU PICO → card select SCK Onboard microSD socket GP18 EDU PICO → card clock MOSI Onboard microSD socket GP19 EDU PICO → card data
How the program uses it The program creates an SPI connection, mounts the card as a virtual filesystem, writes and reads a test file, then unmounts and deinitializes safely.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 11; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 11: mount, write, and read the microSD card over SPI."""
import time
import board
import busio
import digitalio
import storage
import adafruit_sdcard
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
spi = busio.SPI(board.GP18, MOSI=board.GP19, MISO=board.GP16)
chip_select = digitalio.DigitalInOut(board.GP17)
mounted = False
try:
show_module(oled, 11, "SD Card", ("Testing SPI card...",))
sdcard = adafruit_sdcard.SDCard(spi, chip_select)
filesystem = storage.VfsFat(sdcard)
storage.mount(filesystem, "/sd")
mounted = True
with open("/sd/test.txt", "w") as output_file:
output_file.write("SD Card OK!\n")
with open("/sd/test.txt", "r") as input_file:
result = input_file.readline().strip()
show_module(oled, 11, "SD Card", (
"SCK18 MOSI19",
"MISO16 CS17",
"Read: " + result,
))
print("SD card test:", result)
while True:
time.sleep(1)
finally:
if mounted:
storage.umount(filesystem)
chip_select.deinit()
spi.deinit()
i2c.deinit()
Open 11_sd_card.py
Hardware Module 10: Flash-log switch
Learning goal Read the active-low slide switch used to enable flash logging.
What the device does The flash-log switch is a digital input device . It lets a user enable or disable logging without changing the program. Like the push buttons, it uses active-low logic.
Flash-log switch on EDU PICO The physical switch is labelled LOG DATA TO PICO'S FLASH . Its position is read separately from the act of writing data.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 179–183.
Interfacing connection Switch signal EDU PICO connection CircuitPython pin Meaning LOG switch output Onboard flash-log switch GP15 Low = logging selected; high = not selected OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Shows switch state
How the program uses it The program reports changes of the active-low GP15 slide switch. This standalone lesson displays the logging selection; it does not write a flash log.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 12; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 12: read the active-low flash-log slide switch on GP15."""
import time
import board
import digitalio
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
log_switch = digitalio.DigitalInOut(board.GP15)
log_switch.switch_to_input()
last_value = None
try:
while True:
enabled = not log_switch.value
if enabled != last_value:
status = "Enabled" if enabled else "Disabled"
show_module(oled, 12, "Log to Flash", (
"Switch: GP15",
"Active-low input",
"Logging: " + status,
))
print("Flash logging:", status)
last_value = enabled
time.sleep(0.05)
finally:
log_switch.deinit()
i2c.deinit()
Open 12_log_switch.py
Hardware Module 11: Capacitive keypad
Learning goal Decode the Seeed 3x4 keypad UART byte values.
What the device does The 3×4 capacitive keypad is a touch input sensor . Its controller detects a touched key and sends a key code over UART. Capacitive sensing requires no mechanical switch movement.
Project extension hardware The capacitive keypad is not shown in the supplied 202405 EDU PICO Booklet V2.0. Use the verified UART wiring table below and the photograph/documentation supplied with the keypad rather than an unrelated booklet image.
Interfacing connection Keypad signal EDU PICO Grove/UART port CircuitPython pin Direction Keypad RX UART receive terminal on keypad GP20 TX EDU PICO → keypad Keypad TX UART transmit terminal on keypad GP21 RX Keypad output → EDU PICO VCC/GND UART Grove port power 3V3/GND Module power/common reference
Cross the UART data wires Keypad RX connects to EDU PICO TX GP20, while keypad TX connects to EDU PICO RX GP21.
How the program uses it The program reads one byte at 9600 baud and uses a dictionary to map the received hexadecimal code to a keypad character.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 16; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 16: read the Seeed 3x4 capacitive keypad through UART."""
import time
import board
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
KEYS = {
0xE1: "1", 0xE2: "2", 0xE3: "3",
0xE4: "4", 0xE5: "5", 0xE6: "6",
0xE7: "7", 0xE8: "8", 0xE9: "9",
0xEA: "*", 0xEB: "0", 0xEC: "#",
}
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
uart = busio.UART(
tx=board.GP20,
rx=board.GP21,
baudrate=9600,
timeout=0.01,
)
history = ""
show_module(oled, 16, "Cap. Keypad", (
"Pico TX GP20 -> RX",
"Pico RX GP21 <- TX",
"Touch a key",
))
try:
while True:
data = uart.read(1)
if data:
key = KEYS.get(data[0], "?")
history = (history + key)[-8:]
show_module(oled, 16, "Cap. Keypad", (
"TX GP20 / RX GP21",
"Last key: " + key,
"Keys: " + history,
))
print("Key:", key, "raw: 0x{:02X}".format(data[0]))
else:
time.sleep(0.01)
finally:
uart.deinit()
i2c.deinit()
Open 16_capacitive_keypad.py
Hardware Module 12: WS2812 RGB LEDs
Learning goal Control five addressable LEDs and cycle through named RGB colours.
What the device does A WS2812 is a digitally controlled RGB LED actuator . Each LED contains red, green, and blue elements plus a controller, allowing one data wire to set the colour of every LED in a chain.
RGB LEDs on EDU PICO The five numbered LEDs form one addressable chain beside the buttons. Select the picture to enlarge it.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 67–71.
Interfacing connection LED signal EDU PICO connection CircuitPython pin Purpose DIN Onboard RGB LED chain GP14 Serial colour data for five LEDs Power/Ground Onboard supply Board-managed Powers the LED chain OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Shows the selected colour
How the program uses it The program cycles through named RGB tuples, applies a safe brightness setting, and writes each colour to all five LEDs.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 02; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 02: cycle the five WS2812 LEDs on GP14 through eight colours."""
import time
import board
import busio
import neopixel
import adafruit_ssd1306
COLOURS = (
("RED", (255, 0, 0)),
("ORANGE", (255, 180, 0)),
("YELLOW", (80, 80, 0)),
("GREEN", (0, 255, 0)),
("CYAN", (0, 255, 255)),
("BLUE", (0, 0, 255)),
("PURPLE", (180, 0, 255)),
("WHITE", (100, 100, 100)),
)
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
pixels = neopixel.NeoPixel(board.GP14, 5, brightness=0.1, auto_write=True)
try:
while True:
for name, colour in COLOURS:
pixels.fill(colour)
oled.fill(0)
oled.text('(2) NeoPixel RGB', 0, 0, 1)
oled.text('Data: GP14', 0, 16, 1)
oled.text('LED count: 5', 0, 28, 1)
oled.text('Colour: ' + name, 0, 40, 1)
oled.show()
print("Colour:", name)
time.sleep(0.8)
finally:
pixels.fill((0, 0, 0))
pixels.deinit()
i2c.deinit()
Open 02_ws2812_rgb_led.py
Hardware Module 13: Audio and buzzer
Learning goal Play a repeating melody using PWM frequency and duty cycle.
What the device does A passive piezo buzzer is a sound-producing actuator . It requires a changing electrical signal; the signal frequency determines pitch and its duration determines note length. EDU PICO also provides a separate audio output.
Audio and buzzer on EDU PICO Set the onboard audio/buzzer selector to the buzzer path before expecting sound from the piezo device.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 28–35.
Interfacing connection Audio signal EDU PICO connection CircuitPython pin Purpose Buzzer drive Onboard passive buzzer GP21 PWM frequency produces a musical tone Audio output Onboard audio jack/path GP20 Alternative audio signal path OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Displays note information
How the program uses it The program represents a melody as frequency-duration pairs, changes PWM frequency for each note, and turns the output off for rests.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 10; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 10: play a repeating melody on the passive buzzer at GP21."""
import time
import board
import pwmio
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
MELODY = (
(2637, 0.15), (2637, 0.15), (0, 0.15), (2637, 0.15),
(0, 0.15), (2093, 0.15), (2637, 0.15), (0, 0.15),
(3136, 0.30), (0, 0.30), (1568, 0.30), (0, 0.30),
)
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
buzzer = pwmio.PWMOut(
board.GP21,
frequency=440,
duty_cycle=0,
variable_frequency=True,
)
show_module(oled, 10, "Audio & Buzzer", (
"Buzzer: GP21",
"Audio output: GP20",
"Playing melody",
))
try:
while True:
for frequency, duration in MELODY:
if frequency:
buzzer.frequency = frequency
buzzer.duty_cycle = 32768
else:
buzzer.duty_cycle = 0
time.sleep(duration)
buzzer.duty_cycle = 0
time.sleep(0.5)
finally:
buzzer.duty_cycle = 0
buzzer.deinit()
i2c.deinit()
Open 10_audio_buzzer.py
Hardware Module 14: Servo motor
Learning goal Control servo angle with the onboard potentiometer.
What the device does A hobby servo is a position-controlled rotary actuator . An internal controller moves its shaft to the angle commanded by a repeating PWM pulse. The potentiometer supplies the user's requested position.
Servo ports on EDU PICO Observe the printed S, +, − order. The booklet identifies orange/yellow as signal, red as positive, and brown/black as ground.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 86–90.
Interfacing connection Device signal EDU PICO Grove/board port CircuitPython pin Direction/purpose Servo signal Servo port GP6 EDU PICO → servo PWM command Servo V+/GND Servo power port External/board supply and GND Motor power; grounds must be common Potentiometer SIG Onboard analogue input GP28 / ADC2 User position command → EDU PICO OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Displays commanded angle
How the program uses it The GP28 potentiometer sets a 0–180° command for adafruit_motor.servo.Servo on GP6. PWM runs at 50 Hz with a 500–2500 microsecond pulse range. The OLED shows ADC value, angle and potentiometer percentage; cleanup releases the servo signal.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 13; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 13: control the GP6 servo angle with the GP28 potentiometer."""
import time
import board
import busio
import analogio
import pwmio
import adafruit_ssd1306
from adafruit_motor import servo
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
servo_pwm = pwmio.PWMOut(board.GP6, frequency=50, duty_cycle=0)
# Preserve the previous 500–2500 microsecond range for 0–180 degrees.
servo_motor = servo.Servo(servo_pwm, min_pulse=500, max_pulse=2500)
potentiometer = analogio.AnalogIn(board.GP28)
try:
while True:
raw = potentiometer.value
angle = int(raw * 180 / 65535)
percent = raw * 100 / 65535
servo_motor.angle = angle
oled.fill(0)
oled.text('(13) Servo', 0, 0, 1)
oled.text('ADC GP28: {}'.format(raw), 0, 14, 1)
oled.text('Angle: {} degrees'.format(angle), 0, 26, 1)
oled.text('Pot position: {:.0f}%'.format(percent), 0, 38, 1)
oled.text('Servo GP6 / 50 Hz', 0, 50, 1)
oled.show()
print("Servo angle:", angle)
time.sleep(0.05)
finally:
servo_motor.angle = None
servo_pwm.deinit()
potentiometer.deinit()
i2c.deinit()
Open 13_servo_motor.py
Hardware Module 15: DC motors
Learning goal Ramp Motor 2 in both directions and brake before reversing.
What the device does A brushed DC motor is a continuous-rotation actuator . An H-bridge driver reverses current for forward/reverse motion and applies PWM to control speed. Never connect a motor directly to a GPIO pin.
DC motor driver on EDU PICO Motor 1 and Motor 2 use separate screw terminals and driver channels. The nearby test buttons help verify wiring independently of code.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 124–129.
Interfacing connection Motor-driver signal EDU PICO terminal/driver CircuitPython pin Purpose Motor 1 input A/B Onboard motor driver channel 1 GP10 / GP11 Unused in this standalone program Motor 2 input A/B Onboard motor driver channel 2 GP12 / GP13 Direction and PWM speed Motor outputs M1/M2 screw terminals Driver outputs Driver → motor power Motor supply/GND Motor power input External supply/common GND Supplies motor current safely
How the program uses it Only Motor 2 is initialized on GP12/GP13. Its requested drive rises from 0% to 100% in 5% increments and falls to 0%, with each nonzero level held for 0.25 s plus display and processing time. The motor brakes for 1.5 s before the opposite direction; CCW then CW repeat. OLED and serial output show direction, PWM command, requested percentage and status. The percentage is a command, not measured RPM. Zero throttle applies braking; PWM command 0 describes zero drive rather than the individual brake input levels. Motor 1 on GP10/GP11 is unused.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 14; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 14: ramp Motor 2 up/down in CCW, then CW, with a stopped pause."""
import time
import board
import pwmio
from adafruit_motor import motor
import busio
import adafruit_ssd1306
def show_motor_status(direction, percent, status):
# Percentage is the requested drive level, not a measured motor RPM.
duty = int(percent * 65535 / 100)
oled.fill(0)
oled.text('(14) DC Motor 2', 0, 0, 1)
oled.text('Direction: ' + direction, 0, 14, 1)
oled.text('PWM cmd: {}'.format(duty), 0, 26, 1)
oled.text('Speed cmd: {}%'.format(percent), 0, 38, 1)
oled.text(status, 0, 50, 1)
oled.show()
print('{} | PWM: {} | Speed: {}% | {}'.format(direction, duty, percent, status))
RAMP_STEP_PERCENT = 5
RAMP_DELAY = 0.25
DIRECTION_PAUSE = 1.5
i2c = busio.I2C(board.GP5, board.GP4, frequency=400000)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
motor_pwms = (
pwmio.PWMOut(board.GP12, frequency=10000),
pwmio.PWMOut(board.GP13, frequency=10000),
)
motor_2 = motor.DCMotor(motor_pwms[0], motor_pwms[1])
motor_2.throttle = 0
def set_speed(direction, sign, percent, status):
throttle = sign * percent / 100
motor_2.throttle = throttle
show_motor_status(direction, percent, status)
def run_direction(direction, sign):
# Positive throttle follows the existing EDU PICO CCW connection.
for percent in range(RAMP_STEP_PERCENT, 101, RAMP_STEP_PERCENT):
set_speed(direction, sign, percent, 'Increasing')
time.sleep(RAMP_DELAY)
for percent in range(100 - RAMP_STEP_PERCENT, 0, -RAMP_STEP_PERCENT):
set_speed(direction, sign, percent, 'Decreasing')
time.sleep(RAMP_DELAY)
# Zero throttle brakes Motor 2 before applying the opposite direction.
set_speed(direction, sign, 0, 'Stopped {:.1f} s'.format(DIRECTION_PAUSE))
time.sleep(DIRECTION_PAUSE)
try:
while True:
run_direction('CCW', 1)
run_direction('CW', -1)
finally:
motor_2.throttle = 0
for pwm in motor_pwms:
pwm.deinit()
i2c.deinit()
Open 14_dc_motor.py
Hardware Module 16: USB relay
Learning goal Toggle the EDU PICO USB power relay.
What the device does The USB relay is a power-switching actuator . A low-current GPIO control signal operates the onboard switching circuit, allowing the EDU PICO to turn power to a USB load on or off.
USB relay on EDU PICO The switched USB output is controlled through GP22. Connect only a suitable low-power USB load for the classroom test.Connection reference: supplied EDU PICO Booklet V2.0, pp. 12 and 130–150.
Interfacing connection Relay signal EDU PICO connection CircuitPython pin Purpose Relay control Onboard USB relay circuit GP22 Digital output switches USB power USB load Switched USB output Relay power path Receives power when enabled OLED I2C Onboard I2C bus SDA GP4, SCL GP5 Displays relay state
How the program uses it The program changes a digital output at timed intervals and reports whether USB power is on or off.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 15; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 15: toggle the EDU PICO USB power relay on GP22."""
import time
import board
import digitalio
import busio
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
usb_relay = digitalio.DigitalInOut(board.GP22)
usb_relay.switch_to_output(value=False)
try:
while True:
usb_relay.value = not usb_relay.value
status = "Enabled" if usb_relay.value else "Disabled"
show_module(oled, 15, "USB Relay", (
"Control: GP22",
"USB power:",
status,
))
print("USB relay:", status)
time.sleep(1.5)
finally:
usb_relay.value = False
usb_relay.deinit()
i2c.deinit()
Open 15_usb_relay.py
Hardware Module 17: Stepper motor
Learning goal Rotate a 28BYJ-48 in alternating directions using half-steps and timed OLED updates.
What the device does A stepper motor is an incremental-position actuator . Energising its coils in a defined sequence turns the shaft by small, repeatable steps. A ULN2003 driver supplies the coil current that GPIO pins cannot provide directly.
Project extension hardware The stepper motor and ULN2003 board are not depicted in the supplied 202405 EDU PICO Booklet V2.0. The verified GP26, GP27, GP8, and GP7 connection table remains the authoritative wiring for this lesson.
Interfacing connection ULN2003 signal EDU PICO connection CircuitPython pin Purpose IN1 Digital output GP26 Stepper coil sequence channel 1 IN2 Digital output GP27 Stepper coil sequence channel 2 IN3 Digital output GP8 Stepper coil sequence channel 3 IN4 Digital output GP7 Stepper coil sequence channel 4 VCC/GND Driver motor supply External supply/common GND Supplies motor current safely
How the program uses it The program uses adafruit_motor.stepper.StepperMotor with IN1, IN3, IN2, IN4 constructor order (GP26, GP8, GP27, GP7), microsteps=None and INTERLEAVE half-steps. Each nominal 4,096-call revolution ramps from 6 ms to 4 ms per step and slows near its endpoint, then releases the coils for a two-second pause before reversing. Allow at least about 16.4 s plus ramps and processing per turn. OLED step count and estimated angle are sampled once per second; short partial transfers run in idle slots with at least 3 ms remaining. Full-screen transfers occur at movement boundaries. The angle follows commanded steps, increases CCW on the kit scale and wraps at 360°; it is not an encoder measurement. Physical direction depends on wiring and viewing position. This standalone lesson has no navigation-button controls.
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 17; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 17: rotate a 28BYJ-48 stepper through a ULN2003 driver."""
import time
import board
import digitalio
import busio
import adafruit_ssd1306
from adafruit_motor import stepper
class ValueDisplay:
"""Send only the two changing OLED rows, in short idle-time transactions."""
def __init__(self, oled, i2c):
self.oled = oled
self.i2c = i2c
self.buffer = getattr(oled, 'buffer', None)
self.partial = (self.buffer is not None and len(self.buffer) == 1025
and self.buffer[0] == 0x40
and not getattr(oled, 'page_addressing', False))
self.pages = bytearray(256)
self.command = bytearray((0x00, 0x21, 0, 15, 0x22, 3, 3))
self.packet = bytearray(17)
self.packet[0] = 0x40
self.cancel()
def cancel(self):
self.busy = False
def queue(self, step, angle, total_steps=4096):
self.labels = ('Step: {}/{}'.format(step, total_steps), 'Est angle: {:.1f} deg'.format(angle))
self.row = 0
self.offset = 0
self.busy = True
def service(self):
if not self.busy:
return
if self.row < 2:
# Render one row per idle slot; do not redraw the full screen.
y = 24 if self.row == 0 else 40
self.oled.fill_rect(0, y, 128, 8, 0)
self.oled.text(self.labels[self.row], 0, y, 1)
if self.partial:
start = 1 + (y // 8) * 128
self.pages[self.row * 128:(self.row + 1) * 128] = self.buffer[start:start + 128]
self.row += 1
return
if not self.partial:
# The desktop simulator represents OLED commands rather than a framebuffer.
if hasattr(self.oled, 'commands'):
self.oled.show()
# An unrecognised hardware framebuffer gets endpoint updates only.
self.busy = False
return
if not self.i2c.try_lock():
return
try:
page = 3 if self.offset < 128 else 5
column = self.offset % 128
self.command[2] = column
self.command[3] = column + 15
self.command[5] = page
self.command[6] = page
self.packet[1:] = self.pages[self.offset:self.offset + 16]
self.i2c.writeto(0x3C, self.command)
self.i2c.writeto(0x3C, self.packet)
finally:
self.i2c.unlock()
self.offset += 16
if self.offset == 256:
self.busy = False
PINS = (board.GP26, board.GP27, board.GP8, board.GP7)
STEPS_PER_ROTATION = 4096
STEP_DELAY = 0.004 # Slower target: 250 half-steps/second before processing overhead.
START_DELAY = 0.006 # Start and finish each movement more gently.
RAMP_STEPS = 256
PAUSE_SECONDS = 2.0
DISPLAY_INTERVAL = 1.0
OLED_IDLE_BUDGET = 0.003 # Service the OLED only with at least 3 ms until the next step.
i2c = busio.I2C(board.GP5, board.GP4, frequency=400000)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
value_display = ValueDisplay(oled, i2c)
outputs = []
for pin_name in PINS:
output = digitalio.DigitalInOut(pin_name)
output.switch_to_output(value=False)
outputs.append(output)
# Adafruit expects the driver inputs in IN1, IN3, IN2, IN4 order.
stepper_motor = stepper.StepperMotor(
outputs[0], outputs[2], outputs[1], outputs[3], microsteps=None
)
direction = 1
current_step = 0
position_steps = 0
next_step = time.monotonic()
pause_until = 0
def display_angle():
# Match the kit's printed scale: angles increase counter-clockwise.
return (-position_steps * 360 / STEPS_PER_ROTATION) % 360
def update_display(status):
# Full transfers happen only before motion starts or after it has stopped.
value_display.cancel()
oled.fill(0)
oled.text('(17) Stepper Motor', 0, 0, 1)
oled.text('Clockwise' if direction > 0 else 'Counter-clockwise', 0, 12, 1)
oled.text('Step: {}/{}'.format(current_step, STEPS_PER_ROTATION), 0, 24, 1)
oled.text('Est angle: {:.1f} deg'.format(display_angle()), 0, 40, 1)
oled.text(status, 0, 56, 1)
oled.show()
update_display("Running")
next_step = time.monotonic()
next_display = next_step + DISPLAY_INTERVAL
print("Direction: Clockwise")
try:
while True:
now = time.monotonic()
if pause_until:
if now < pause_until:
time.sleep(0.001)
continue
pause_until = 0
direction *= -1
current_step = 0
next_step = now
label = "Clockwise" if direction > 0 else "Counter-clockwise"
update_display("Running")
next_step = time.monotonic()
next_display = next_step + DISPLAY_INTERVAL
print("Direction:", label)
if now < next_step:
if next_step - now >= OLED_IDLE_BUDGET:
if now >= next_display and not value_display.busy:
value_display.queue(current_step, display_angle(),
STEPS_PER_ROTATION)
next_display = now + DISPLAY_INTERVAL
if value_display.busy:
value_display.service()
else:
time.sleep(0.0001)
else:
time.sleep(0.0001)
continue
# BACKWARD follows the original increasing IN1–IN4 coil sequence.
stepper_motor.onestep(
direction=stepper.BACKWARD if direction > 0 else stepper.FORWARD,
style=stepper.INTERLEAVE,
)
current_step += 1
position_steps += direction
ramp_progress = min(current_step, STEPS_PER_ROTATION - current_step, RAMP_STEPS)
step_delay = START_DELAY - (START_DELAY - STEP_DELAY) * ramp_progress / RAMP_STEPS
next_step = time.monotonic() + step_delay
if current_step == STEPS_PER_ROTATION:
stepper_motor.release()
update_display("Paused")
pause_until = time.monotonic() + PAUSE_SECONDS
finally:
stepper_motor.release()
for output in outputs:
output.deinit()
i2c.deinit()
Open 17_stepper_motor.py
Hardware Module 18: Four-digit display
Learning goal Count from 0000 to 9999 on the TM1650 display.
What the device does The TM1650 four-digit seven-segment display is a visual-output actuator . Its driver scans the LED digits and receives brightness and segment data through I2C, reducing the number of GPIO connections required.
Project extension hardware The external TM1650 four-digit display is not depicted in the supplied 202405 EDU PICO Booklet V2.0. Follow the verified I2C Grove connection table and the actual module labels.
Interfacing connection Display signal EDU PICO Grove/board port CircuitPython pin Purpose SDA I2C Grove port GP4 EDU PICO → TM1650 command/data SCL I2C Grove port GP5 I2C clock VCC/GND I2C Grove port power 3V3/GND Display power/common reference
How the program uses it The TM1650Display class from edu_pico_lib handles segment encoding, digit addresses and brightness. The program formats the count and reports it on the four-digit display, the onboard OLED and the serial console using one shared I²C bus.
Before running, copy TM1650Display.py into CIRCUITPY/edu_pico_lib/. The OLED also requires adafruit_ssd1306 in CIRCUITPY/lib/ and its font5x8.bin font file on CIRCUITPY.
Download TM1650Display.py
Revised standalone tutorial Run this file as code.py with CircuitPython 10 and matching libraries. It initializes the OLED directly using busio and adafruit_ssd1306; any show_module function is defined inside this file. The filename and OLED retain tutorial number 18; the sidebar retains the course device order. Keep font5x8.bin on CIRCUITPY and the required drivers in CIRCUITPY/lib/. For the four-digit display, also keep edu_pico_lib/TM1650Display.py alongside code.py.
Complete CircuitPython source
Select any line to reveal its explanation, or use the sidebar controls to expand all code comments.
"""Module 18: count from 0000 to 9999 on the TM1650 display."""
import time
import board
import busio
from edu_pico_lib.TM1650Display import TM1650Display
import adafruit_ssd1306
def show_module(oled, number, title, lines):
"""Draw this lesson's OLED screen without an external helper module."""
oled.fill(0)
oled.text("({}) {}".format(number, title)[:21], 0, 0, 1)
for index, line in enumerate(lines[:4]):
oled.text(str(line)[:21], 0, 16 + index * 11, 1)
oled.show()
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
display = TM1650Display(i2c, brightness=3)
count = 0
try:
while True:
text = "{:04d}".format(count)
display.show(text)
show_module(oled, 18, "4-Digit Display", (
"TM1650 on I2C",
"SDA GP4 / SCL GP5",
"Display: " + text,
))
print("Display:", text)
count = (count + 1) % 10000
time.sleep(0.1)
finally:
display.off()
i2c.deinit()
Open 18_four_digit_display.py
LABORATORY PRACTICAL 1
Digital Output Student lab manual · EDU PICO / RP2040 · CircuitPython · Parts A–D
Learn to present information using an OLED, RGB LEDs, a seven-segment display and a buzzer. These output devices use different interfaces: I²C display communication, addressable pixel data and a PWM tone signal.
1. Learning outcomes Identify the connections, libraries and commands for all four output devices. Run, explain and modify CircuitPython programs to produce specified outputs. Compare expected and observed outputs, diagnose faults and record retest results. 2. Equipment and preparation EDU PICO with Pico W, a USB data cable, a computer with Thonny, and the external M18 TM1650 four-digit display with a suitable I²C connection. Use the CircuitPython interpreter in Thonny. Record your firmware version from CIRCUITPY/boot_out.txt or the Shell startup banner. Use the Adafruit library bundle matching the firmware major version. Install adafruit_ssd1306.mpy and its required adafruit_bus_device and adafruit_framebuf dependencies, plus neopixel.mpy, in CIRCUITPY/lib. Copy the course TM1650Display.py driver into CIRCUITPY/edu_pico_lib/. Keep the existing board libraries. Disconnect power before changing external wiring. Follow the module labels and the Chapter 2 connection diagrams. Set the audio/buzzer selector to Method 1 for GP21. CircuitPython library bundles · TM1650Display.py
3. Save and run your work Create a LAB1 folder on your computer. Save guided practice separately, then use the exact assignment filenames listed below. Run each full listing separately with Thonny Run (F5). Use Stop or Ctrl+C before running another program; reset the board if a pin or I²C bus is still in use. Files named LAB1_partA.py through LAB1_partD.py do not automatically run at power-up. Run the chosen file in Thonny. If standalone execution is required, keep the named original on your computer and copy only the selected program to CIRCUITPY/code.py after backing up any existing code.py. import board
import neopixel
import adafruit_ssd1306
from edu_pico_lib.TM1650Display import TM1650Display
print("LAB1 imports OK")
Run this import check before Part A. Fix any reported library problem before continuing; this check does not test the wiring or the physical devices.
Part A — OLED display Follow Topic 2.7. The OLED uses SDA on GP4, SCL on GP5, and the course example address 0x3C. The display area is 128 × 64 pixels.
Command / setting Purpose SDA → GP4; SCL → GP5 I²C data and clock; busio.I2C takes SCL first, then SDA. 3V3 / GND Use the board/module power and common ground connections shown in Topic 2.7.
Guided example Read the program section by section below. These excerpts belong to one program; keep the indentation and use the complete runnable listing when copying into Thonny.
1. Imports Load the modules and libraries used by this program.
import time
import board
import busio
import adafruit_ssd1306
2. Initialization Configure the pins, create device objects and set initial values. This runs before the main loop.
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
count = 0
try:
3. Main loop Perform the repeated output operations. A while True loop repeats until stopped; a for loop ends after its listed values have been processed.
while True:
oled.fill(0)
oled.text("EDI4153", 0, 0, 1, size=1)
oled.text("Starting...", 0, 12, 1, size=1)
oled.text("Count: {}".format(count), 0, 24, 1, size=1)
oled.show()
count += 1
time.sleep(1)
4. Cleanup The finally block releases hardware resources when the try block finishes, fails or is interrupted.
finally:
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
i2c = busio.I2C(board.GP5, board.GP4)
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
count = 0
try:
# === 3. MAIN LOOP ===
while True:
oled.fill(0)
oled.text("EDI4153", 0, 0, 1, size=1)
oled.text("Starting...", 0, 12, 1, size=1)
oled.text("Count: {}".format(count), 0, 24, 1, size=1)
oled.show()
count += 1
time.sleep(1)
# === 4. CLEANUP ===
finally:
i2c.deinit()
Command / setting Purpose oled.fill(0) Clear the previous image from the OLED buffer. oled.text(message, x, y, 1, size=1) Draw text at the given top-left pixel coordinate in the normal font size. The 1 means pixels on; size controls text scale. oled.show() Send the completed buffer to the physical OLED. time.sleep(1) Keep each count visible for one second.
Expected result: EDI4153, Starting..., and Count: 0 appear on separate lines. The count updates once per second. Stop the program before the next part.
Practice: change the message, move its x/y position, and change the update interval. Compare size=1 with size=2; use the fourth text argument 0 or 1 to turn pixels off or on.
Assignment A Display your name, matric number and LAB1 Digital Output on separate readable lines using oled.text(). Use a short name if a line is too wide. Keep all text within the screen without overlap. State the x/y coordinates and size chosen for each line. Submit a photograph showing the complete display and explain how oled.show() makes the buffered text visible. Save your completed program as LAB1_partA.py. Keep this file for your assignment submission.
Part B — RGB LED Follow Topic 2.5. The five onboard WS2812 pixels use GP14 and indexes 0–4. Their connections are built into the EDU PICO; no external LED wiring is needed.
Guided example Read the program section by section below. These excerpts belong to one program; keep the indentation and use the complete runnable listing when copying into Thonny.
1. Imports Load the modules and libraries used by this program.
import time
import board
import neopixel
2. Initialization Configure the pins, create device objects and set initial values. This runs before the main loop.
pixels = neopixel.NeoPixel(
board.GP14, 5, brightness=0.1,
auto_write=False, pixel_order=neopixel.GRB)
3. Main loop Perform the repeated output operations. A while True loop repeats until stopped; a for loop ends after its listed values have been processed.
try:
for colour in ((255, 0, 0), (0, 255, 0), (0, 0, 255)):
pixels.fill(colour)
pixels.show()
time.sleep(0.5)
pixels.fill((0, 0, 0))
pixels[0] = (30, 30, 30)
pixels.show()
time.sleep(1)
4. Cleanup The finally block releases hardware resources when the try block finishes, fails or is interrupted.
finally:
pixels.fill((0, 0, 0))
pixels.show()
pixels.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import neopixel
# === 2. INITIALIZATION ===
pixels = neopixel.NeoPixel(
board.GP14, 5, brightness=0.1,
auto_write=False, pixel_order=neopixel.GRB)
# === 3. MAIN LOOP ===
try:
for colour in ((255, 0, 0), (0, 255, 0), (0, 0, 255)):
pixels.fill(colour)
pixels.show()
time.sleep(0.5)
pixels.fill((0, 0, 0))
pixels[0] = (30, 30, 30)
pixels.show()
time.sleep(1)
# === 4. CLEANUP ===
finally:
pixels.fill((0, 0, 0))
pixels.show()
pixels.deinit()
Command / setting Purpose brightness=0.1 Use 10% software brightness. (red, green, blue) Each colour channel ranges from 0 to 255. pixels.fill(...); pixels[0] Set all pixels, or set only the first pixel. auto_write=False; pixels.show() Store changes in the buffer, then send them to the LEDs.
Expected result: all five pixels show red, green and blue for 0.5 seconds each; only pixel 0 then shows dim white for one second; all pixels turn off.
Practice: choose another RGB colour and light only the centre pixel. Explain the difference between changing the pixel buffer and calling show().
Assignment B At brightness 0.1, repeat this status sequence: all pixels green for 2 seconds; all pixels amber for 1 second; only pixel 0 red for 1 second; all pixels off for 1 second. Choose and document the RGB tuple for each colour. Ensure pixels 1–4 are off during the red state. Record a short video of one complete cycle and explain the timing and pixel selection. Save your completed program as LAB1_partB.py. Keep this file for your assignment submission.
Part C — Seven-segment display Follow Topic 2.6. Connect the external TM1650 module with power disconnected: SDA to GP4, SCL to GP5, VCC to the specified 3V3 connection and GND to common ground. Confirm module labels and connector polarity.
Install the course driver before running this example. The driver handles segment patterns and I²C access; the program controls the number and its timing.
TM1650Display.py
Guided example Read the program section by section below. These excerpts belong to one program; keep the indentation and use the complete runnable listing when copying into Thonny.
1. Imports Load the modules and libraries used by this program.
import time
import board
import busio
from edu_pico_lib.TM1650Display import TM1650Display
2. Initialization Configure the pins, create device objects and set initial values. This runs before the main loop.
i2c = busio.I2C(board.GP5, board.GP4)
display = None
try:
display = TM1650Display(i2c, brightness=3)
display.show("1234")
time.sleep(2)
3. Main loop Perform the repeated output operations. A while True loop repeats until stopped; a for loop ends after its listed values have been processed.
while True:
for count in range(100):
display.show("{:04d}".format(count))
time.sleep(0.5)
4. Cleanup The finally block releases hardware resources when the try block finishes, fails or is interrupted.
finally:
try:
if display is not None:
display.off()
finally:
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import busio
from edu_pico_lib.TM1650Display import TM1650Display
# === 2. INITIALIZATION ===
i2c = busio.I2C(board.GP5, board.GP4)
display = None
try:
display = TM1650Display(i2c, brightness=3)
display.show("1234")
time.sleep(2)
# === 3. MAIN LOOP ===
while True:
for count in range(100):
display.show("{:04d}".format(count))
time.sleep(0.5)
# === 4. CLEANUP ===
finally:
try:
if display is not None:
display.off()
finally:
i2c.deinit()
Command / setting Purpose TM1650Display(i2c, brightness=3) Initialize the display; brightness levels are 1–7. display.show("1234") Display four fixed digits. "{:04d}".format(count) Format the number as four digits with leading zeros. range(100); time.sleep(0.5) Count from 0 to 99 with a half-second interval. display.off(); i2c.deinit() Turn off the display and release the bus when stopped.
Expected result: 1234 appears for two seconds, then the display repeatedly counts 0000 through 0099 at 0.5-second intervals.
Practice: change the delay and display a different fixed value. Explain what happens when the counter reaches its last value.
Assignment C Count down from 0099 to 0001 continuously, with a 0.1-second interval for each displayed value. Keep four-digit zero padding. After 0001, restart at 0099 without displaying 0000. Record the start, a middle value, and the restart boundary. Explain your loop limits and direction. Save your completed program as LAB1_partC.py. Keep this file for your assignment submission.
Part D — Buzzer Follow Topic 2.9. The onboard buzzer driver uses GP21. Set the audio/buzzer selector downward to Method 1. The buzzer is passive: a changing signal produces the tone.
Guided example Read the program section by section below. These excerpts belong to one program; keep the indentation and use the complete runnable listing when copying into Thonny.
1. Imports Load the modules and libraries used by this program.
import time
import board
import pwmio
2. Initialization Configure the pins, create device objects and set initial values. This runs before the main loop.
buzzer = pwmio.PWMOut(
board.GP21, frequency=440,
duty_cycle=0, variable_frequency=True)
3. Main loop Perform the repeated output operations. A while True loop repeats until stopped; a for loop ends after its listed values have been processed.
try:
for frequency in (440, 880):
buzzer.frequency = frequency
buzzer.duty_cycle = 32768
time.sleep(0.5)
buzzer.duty_cycle = 0
time.sleep(0.5)
4. Cleanup The finally block releases hardware resources when the try block finishes, fails or is interrupted.
finally:
buzzer.duty_cycle = 0
buzzer.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import pwmio
# === 2. INITIALIZATION ===
buzzer = pwmio.PWMOut(
board.GP21, frequency=440,
duty_cycle=0, variable_frequency=True)
# === 3. MAIN LOOP ===
try:
for frequency in (440, 880):
buzzer.frequency = frequency
buzzer.duty_cycle = 32768
time.sleep(0.5)
buzzer.duty_cycle = 0
time.sleep(0.5)
# === 4. CLEANUP ===
finally:
buzzer.duty_cycle = 0
buzzer.deinit()
Command / setting Purpose variable_frequency=True Allow the PWM frequency to change between tones. buzzer.frequency Set pitch in hertz; frequency is not note duration. duty_cycle=32768 Approximately 50% duty cycle produces a repeating drive signal. duty_cycle=0; time.sleep(...) Make silence and control how long the pause lasts. finally; buzzer.deinit() Stop the output and release the PWM resource.
Expected result: a 440 Hz tone for 0.5 seconds, silence for 0.5 seconds, an 880 Hz tone for 0.5 seconds, then silence. The second tone has a higher pitch.
Practice: change the duration while keeping the frequency fixed, then change the frequency while keeping the duration fixed. Describe the difference.
Assignment D Play a notification: 523 Hz for 0.2 seconds, silence for 0.2 seconds, then 784 Hz for 0.2 seconds. Wait one second, then produce three alarm beeps at 1000 Hz, each sounding for 0.2 seconds with a 0.2-second silent gap between beeps. Finish in silence and release the PWM resource. Record a short video with sound and explain frequency, duration and silent gaps. Save your completed program as LAB1_partD.py. Keep this file for your assignment submission.
4. Troubleshooting and retest Symptom Check / action ValueError: incompatible .mpy file Replace incompatible libraries with the firmware-matching bundle; replace complete library folders, then restart and rerun the import check. ImportError Check the library filename and folder. TM1650Display.py belongs in edu_pico_lib; Adafruit libraries belong in lib. Blank OLED / clipped text Check SDA/SCL, address, driver, oled.text() coordinates, and that oled.show() follows drawing. Shorten long lines or reduce size. I²C or pin already in use Stop the previous program and run cleanup. Reset before changing parts if resources remain allocated. RGB colours do not update Check GP14, pixel indexes and pixels.show() when auto_write=False. No buzzer sound Check GP21, the Method 1 selector and a nonzero duty cycle during the tone.
5. Assignment submission checklist Part Device Required filename A OLED LAB1_partA.py B RGB LED LAB1_partB.py C Seven-segment display LAB1_partC.py D Buzzer LAB1_partD.py
Submit all four named Python files through the e-learning system using the submission link, and follow the deadline stated in that link. Include a labelled connection table, photographs or short videos, a short explanation of your changes for each part. Identify your name and matric number in a comment at the top of each assignment file. Keep the guided practice separate from your completed assignment. Record any fault found, the correction made and the retest result. Be ready to demonstrate and explain your own program. 2.7 OLED · 2.5 RGB LED · 2.6 Seven-segment · 2.9 Buzzer
Adafruit SSD1306 API · NeoPixel API · CircuitPython PWMOut
LABORATORY PRACTICAL 2
PWM Student lab manual · EDU PICO / RP2040 · CircuitPython · Parts A–C
This lab controls a servo, stepper motor, and DC motor. PWM sets servo position and DC motor speed; the stepper example uses an ordered coil sequence. Complete each part and its assignment before proceeding to the next part.
1. Learning outcomes Explain PWM frequency and duty cycle and identify how they are used by a servo and a DC motor. Use a digital coil sequence to control stepper direction and step count. Run, explain, modify, and safely stop motor-control programs. 2. Equipment and preparation EDU PICO with RP2040, USB data cable, computer with Thonny, and compatible CircuitPython firmware. Servo motor connected to the designated servo port (signal GP6); 28BYJ-48 stepper with ULN2003 driver; DC motor connected through the EDU PICO HX1515H H-bridge. Ensure the Adafruit Motor library is installed in CIRCUITPY/lib. Use the course EDU PICO helper library for the OLED status display. Disconnect power before changing motor wiring. Use the onboard driver and its specified supply; never connect a motor directly to an RP2040 GPIO pin. 3. PWM and motor-control concepts PWM frequency is the number of signal cycles per second. Duty cycle is the fraction of each cycle for which the signal is on. The servo example uses a 50 Hz signal. Pulse width represents the requested angle; use the demonstrated range and do not force the servo against a mechanical stop. The DC motor driver accepts throttle from −1.0 to +1.0. Zero means stop; the sign selects direction and magnitude requests drive level. The stepper advances when the four driver inputs follow a coil sequence. Step count sets approximate rotation; step delay affects speed. 4. Save and run your work Create a LAB2 folder on your computer. Save guided examples separately from your assignment files. Run one complete program at a time in Thonny. Stop it before connecting another motor or changing wiring. If an import fails, check that the library is compatible with the CircuitPython firmware and is in CIRCUITPY/lib. 5. Practical parts and assignments Part A — Servo motor — position control The EDU PICO servo signal is on GP6. The example uses a 50 Hz PWM signal and requests a sequence of angles. Connect the servo to the designated servo port; do not power it from a GPIO pin.
Guided example Study each section in order. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and libraries used by this example.
import time
import board
import pwmio
import busio
import adafruit_ssd1306
2. Initialization Configure the motor connection and initial values before movement starts.
def set_angle(pwm, angle):
pulse_us = 500 + angle * 2000 / 180
pwm.duty_cycle = int(pulse_us * 50 * 65535 / 1000000)
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
servo = pwmio.PWMOut(board.GP6, frequency=50, duty_cycle=0)
3. Main loop Run the specified movement sequence. Observe how each command changes the output.
try:
for angle in (0, 90, 180):
set_angle(servo, angle)
oled.fill(0)
oled.text("\n".join((
'Servo',
'Signal: GP6',
'Angle: {} deg'.format(angle),
'Hold: 1 second'
)), 0, 0, 1, size=1)
oled.show()
print("Servo angle:", angle)
time.sleep(1)
4. Cleanup Stop the output and release hardware resources, including when the program is interrupted.
finally:
servo.duty_cycle = 0
servo.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import pwmio
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
def set_angle(pwm, angle):
pulse_us = 500 + angle * 2000 / 180
pwm.duty_cycle = int(pulse_us * 50 * 65535 / 1000000)
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
servo = pwmio.PWMOut(board.GP6, frequency=50, duty_cycle=0)
# === 3. MAIN LOOP ===
try:
for angle in (0, 90, 180):
set_angle(servo, angle)
oled.fill(0)
oled.text("\n".join((
'Servo',
'Signal: GP6',
'Angle: {} deg'.format(angle),
'Hold: 1 second'
)), 0, 0, 1, size=1)
oled.show()
print("Servo angle:", angle)
time.sleep(1)
# === 4. CLEANUP ===
finally:
servo.duty_cycle = 0
servo.deinit()
i2c.deinit()
Expected result Expected result: the guided example moves the servo to 0°, 90°, and 180°, holding each position for one second, then stops the PWM output. The OLED and serial console show the requested angle at each position.
Practice Change the order of the guided angles, then restore 0°, 90°, 180°, and stop. Explain why the servo signal frequency remains fixed while the pulse width changes.
Assignment A Select at least four different servo angles within the safe operating range of your servo. Move through your selected positions in ascending order, holding at each position for 1.5 seconds. Then return through the same positions in reverse order, again holding at each position for 1.5 seconds. Display the current angle and whether the servo is moving outward or returning on the OLED and serial console. Demonstrate your scan and explain how the PWM pulse sets each angle. Save your program as LAB2_partA.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
Part B — Stepper motor — step sequence Use the 28BYJ-48 stepper with its ULN2003 driver. The EDU PICO control pins are GP26, GP27, GP8, and GP7. This motor advances through a digital coil sequence; its step delay controls movement speed.
Guided example Study each section in order. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and libraries used by this example.
import time
import board
import digitalio
import busio
import adafruit_ssd1306
2. Initialization Configure the motor connection and initial values before movement starts.
PINS = (board.GP26, board.GP27, board.GP8, board.GP7)
SEQUENCE = (
(1, 0, 0, 0), (1, 1, 0, 0),
(0, 1, 0, 0), (0, 1, 1, 0),
(0, 0, 1, 0), (0, 0, 1, 1),
(0, 0, 0, 1), (1, 0, 0, 1),
)
STEP_DELAY = 0.0015
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
outputs = []
for pin in PINS:
output = digitalio.DigitalInOut(pin)
output.switch_to_output(value=False)
outputs.append(output)
phase = 0
direction = 1
3. Main loop Run the specified movement sequence. Observe how each command changes the output.
try:
for step in range(512):
phase = (phase + direction) % len(SEQUENCE)
for output, value in zip(outputs, SEQUENCE[phase]):
output.value = bool(value)
time.sleep(STEP_DELAY)
oled.fill(0)
oled.text("\n".join((
'Stepper',
'512 half-steps',
'Approx. 45 deg',
'Hold: 1 second'
)), 0, 0, 1, size=1)
oled.show()
time.sleep(1) # Keep the coils energized to hold position.
4. Cleanup Stop the output and release hardware resources, including when the program is interrupted.
finally:
for output in outputs:
output.value = False
output.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import digitalio
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
PINS = (board.GP26, board.GP27, board.GP8, board.GP7)
SEQUENCE = (
(1, 0, 0, 0), (1, 1, 0, 0),
(0, 1, 0, 0), (0, 1, 1, 0),
(0, 0, 1, 0), (0, 0, 1, 1),
(0, 0, 0, 1), (1, 0, 0, 1),
)
STEP_DELAY = 0.0015
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
outputs = []
for pin in PINS:
output = digitalio.DigitalInOut(pin)
output.switch_to_output(value=False)
outputs.append(output)
phase = 0
direction = 1
# === 3. MAIN LOOP ===
try:
for step in range(512):
phase = (phase + direction) % len(SEQUENCE)
for output, value in zip(outputs, SEQUENCE[phase]):
output.value = bool(value)
time.sleep(STEP_DELAY)
oled.fill(0)
oled.text("\n".join((
'Stepper',
'512 half-steps',
'Approx. 45 deg',
'Hold: 1 second'
)), 0, 0, 1, size=1)
oled.show()
time.sleep(1) # Keep the coils energized to hold position.
# === 4. CLEANUP ===
finally:
for output in outputs:
output.value = False
output.deinit()
i2c.deinit()
Expected result Expected result: using the course estimate of 4,096 half-steps per revolution, the motor turns 360° counterclockwise (4,096 half-steps), holds for 2 seconds, turns 180° clockwise (2,048 half-steps), holds for 2 seconds, then turns 270° counterclockwise (3,072 half-steps). Keep the coils energized during both holds.
Practice Change direction from 1 to −1 and observe the reverse sequence. Change the number of steps and STEP_DELAY; describe their effects on rotation and speed. Keep the coils energized during a position hold.
Assignment B Program the stepper to rotate 360° counterclockwise, hold its position for 2 seconds, rotate 180° clockwise, hold for 2 seconds, and finally rotate 270° counterclockwise. Use the course estimate of 4,096 half-steps per revolution to calculate each step count. Keep the coils energized during the two holds. Demonstrate the sequence and explain how the coil sequence sets direction. Save your program as LAB2_partB.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
Part C — DC motor — speed and direction DC motor channel 1 uses GP10 and GP11; channel 2 uses GP12 and GP13. Use the EDU PICO HX1515H H-bridge driver. In the Adafruit motor API, throttle ranges from −1.0 to +1.0; zero stops the motor and the sign selects direction.
Guided example Study each section in order. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and libraries used by this example.
import time
import board
import pwmio
from adafruit_motor import motor
import busio
import adafruit_ssd1306
2. Initialization Configure the motor connection and initial values before movement starts.
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
motor_pwms = (
pwmio.PWMOut(board.GP10, frequency=10000),
pwmio.PWMOut(board.GP11, frequency=10000),
)
dc_motor = motor.DCMotor(motor_pwms[0], motor_pwms[1])
3. Main loop Run the specified movement sequence. Observe how each command changes the output.
try:
states = (
("Counterclockwise", -0.5, 2),
("Stop", 0, 1),
("Clockwise", 1.0, 2),
("Stop", 0, 1),
("Counterclockwise", -0.75, 2),
("Stop", 0, 1),
)
for label, throttle, duration in states:
dc_motor.throttle = throttle
oled.fill(0)
oled.text("\n".join((
'DC Motor',
'GP10 / GP11',
label,
'Throttle: {}'.format(throttle)
)), 0, 0, 1, size=1)
oled.show()
print(label, throttle)
time.sleep(duration)
4. Cleanup Stop the output and release hardware resources, including when the program is interrupted.
finally:
dc_motor.throttle = 0
for pwm in motor_pwms:
pwm.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import pwmio
from adafruit_motor import motor
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
motor_pwms = (
pwmio.PWMOut(board.GP10, frequency=10000),
pwmio.PWMOut(board.GP11, frequency=10000),
)
dc_motor = motor.DCMotor(motor_pwms[0], motor_pwms[1])
# === 3. MAIN LOOP ===
try:
states = (
("Counterclockwise", -0.5, 2),
("Stop", 0, 1),
("Clockwise", 1.0, 2),
("Stop", 0, 1),
("Counterclockwise", -0.75, 2),
("Stop", 0, 1),
)
for label, throttle, duration in states:
dc_motor.throttle = throttle
oled.fill(0)
oled.text("\n".join((
'DC Motor',
'GP10 / GP11',
label,
'Throttle: {}'.format(throttle)
)), 0, 0, 1, size=1)
oled.show()
print(label, throttle)
time.sleep(duration)
# === 4. CLEANUP ===
finally:
dc_motor.throttle = 0
for pwm in motor_pwms:
pwm.deinit()
i2c.deinit()
Expected result Expected result: the motor runs counterclockwise at throttle −0.5 for two seconds, stops for one second, runs clockwise at throttle +1.0 for two seconds, stops for one second, runs counterclockwise at throttle −0.75 for two seconds, then stops.
Practice Try a throttle magnitude between 0 and 1.0. Compare it with full drive and explain why the motor is set to zero before reversing direction.
Assignment C Run the motor counterclockwise (CCW) at 60% throttle for 2 seconds, stop for 1 second, run it clockwise (CW) at 80% throttle for 2 seconds, stop for 1 second, then run it counterclockwise (CCW) at 40% throttle for 2 seconds and stop. Convert each percentage to the appropriate signed throttle value in your program: negative for CCW and positive for CW. These percentages specify the throttle command, not a measured percentage of motor speed. Demonstrate the sequence and explain how throttle magnitude and sign affect speed and direction. Save your program as LAB2_partC.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
6. Troubleshooting Symptom Check / action Servo does not move to the requested angle Check GP6, servo-port connection, common ground, 50 Hz frequency, pulse calculation, and mechanical range. Stepper vibrates or turns in the wrong direction Check the ULN2003 wiring order against GP26, GP27, GP8, GP7. Verify the coil sequence and reduce speed by increasing STEP_DELAY. DC motor does not run or reverse Check the HX1515H driver, GP10/GP11 channel, motor supply and throttle value. Set throttle to zero before changing direction. ImportError for adafruit_motor Install the matching Adafruit CircuitPython bundle library and restart the board.
7. Assignment submission checklist Submit LAB2_partA.py, LAB2_partB.py, and LAB2_partC.py through the e-learning system using the relevant submission link. Follow the deadline stated in that link. Put your name and matric number in a comment at the top of each file. Include a short demonstration and explain the requested angle, step sequence, throttle, direction, and timing for each part. Make sure every program stops the motor output and releases the resources it uses. 2.8 PWM · 2.10 DC motor · 2.11 Stepper motor · 2.12 Servo motor
LABORATORY PRACTICAL 3
Digital Input Student lab manual · EDU PICO / RP2040 · CircuitPython · Parts A–B
Use the onboard push buttons and a capacitive keypad as digital inputs. The button program reads GPIO logic states; the keypad program receives encoded key data over UART. Complete each part and its assignment before proceeding to the next.
1. Learning outcomes Configure pull-up digital inputs and interpret active-low button states. Detect button press events and use them to update a program state. Read and validate keypad key codes received through UART. Run, explain, modify, and safely stop input programs. 2. Equipment and preparation EDU PICO with RP2040, USB data cable, computer with Thonny, and compatible CircuitPython firmware. Onboard Button A (GP0) and Button B (GP1); Seeed 3×4 capacitive keypad connected to UART. For OLED status output, use the EDU PICO course helper library. The keypad uses Pico TX GP20, Pico RX GP21 and 9600 baud. Check the audio/keypad selector before using GP20/GP21. Disconnect power before changing external connections. 3. Digital-input concepts A pull-up input reads True while the button is released. The active-low button connects the input to ground when pressed, so the reading becomes False. A press event is detected from a change between released and pressed states. A loop that checks the current state alone may repeat an action while a button is held. UART sends serial data using separate transmit and receive wires. Connect TX to the other device RX, agree on the baud rate, and interpret the received byte using the keypad map. 4. Save and run your work Create a LAB3 folder. Keep guided examples separate from the assignment programs. Run one complete program at a time in Thonny. Stop it before changing the keypad wiring or selector. If a library import fails, check that the course EDU PICO helper files are installed on CIRCUITPY. 5. Practical parts and assignments Part A — Push buttons The onboard buttons are active-low: GP0 is Button A and GP1 is Button B. Pull-up inputs read True while released and False while pressed. The program detects a press edge so a held button does not continuously repeat the action.
Guided example Study the example section by section. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and SSD1306 driver used to read input and display its result.
import time
import board
import digitalio
import busio
import adafruit_ssd1306
2. Initialization Configure the input pins or UART connection and set the initial program state.
def make_button(pin):
button = digitalio.DigitalInOut(pin)
button.switch_to_input(pull=digitalio.Pull.UP)
return button
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
button_a = make_button(board.GP0)
button_b = make_button(board.GP1)
count = 0
previous_a = False
previous_b = False
last_display = None
3. Main loop Read input changes, interpret them, and update the displayed result.
try:
while True:
pressed_a = not button_a.value # Active-low: False electrical level means pressed.
pressed_b = not button_b.value
if pressed_a and not previous_a:
count += 1
if pressed_b and not previous_b:
count = 0
state = (pressed_a, pressed_b, count)
if state != last_display:
label_a = "PRESSED" if pressed_a else "released"
label_b = "PRESSED" if pressed_b else "released"
oled.fill(0)
oled.text("\n".join((
'Buttons',
'A GP0: ' + label_a,
'B GP1: ' + label_b,
'Count: {}'.format(count)
)), 0, 0, 1, size=1)
oled.show()
print("A:", label_a, "B:", label_b, "Count:", count)
last_display = state
previous_a = pressed_a
previous_b = pressed_b
time.sleep(0.02)
4. Cleanup Release the input, UART, and I²C resources when the program stops.
finally:
button_a.deinit()
button_b.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import digitalio
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
def make_button(pin):
button = digitalio.DigitalInOut(pin)
button.switch_to_input(pull=digitalio.Pull.UP)
return button
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
button_a = make_button(board.GP0)
button_b = make_button(board.GP1)
count = 0
previous_a = False
previous_b = False
last_display = None
# === 3. MAIN LOOP ===
try:
while True:
pressed_a = not button_a.value # Active-low: False electrical level means pressed.
pressed_b = not button_b.value
if pressed_a and not previous_a:
count += 1
if pressed_b and not previous_b:
count = 0
state = (pressed_a, pressed_b, count)
if state != last_display:
label_a = "PRESSED" if pressed_a else "released"
label_b = "PRESSED" if pressed_b else "released"
oled.fill(0)
oled.text("\n".join((
'Buttons',
'A GP0: ' + label_a,
'B GP1: ' + label_b,
'Count: {}'.format(count)
)), 0, 0, 1, size=1)
oled.show()
print("A:", label_a, "B:", label_b, "Count:", count)
last_display = state
previous_a = pressed_a
previous_b = pressed_b
time.sleep(0.02)
# === 4. CLEANUP ===
finally:
button_a.deinit()
button_b.deinit()
i2c.deinit()
Expected result Expected result: pressing A increments the count once; pressing B resets it to zero. The OLED and serial console show the button states and count. Releasing a button changes its status but does not change the count.
Practice Change which button updates and which resets the counter. Explain why the program compares the current state with the previous state and why the input is inverted.
Assignment A Button A increments the counter by one for each press. Button B resets it to zero for each press. Holding either button must not repeat the action; release and press again to create another event. Display the counter and both button states. Demonstrate the required behavior. Save your program as LAB3_partA.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
Part B — Capacitive keypad The Seeed 3×4 capacitive keypad sends key codes over UART at 9600 baud. Cross the serial connections: Pico TX GP20 connects to keypad RX; Pico RX GP21 connects to keypad TX. The example maps received bytes to digits, * and #.
Guided example Study the example section by section. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and SSD1306 driver used to read input and display its result.
import time
import board
import busio
import adafruit_ssd1306
2. Initialization Configure the input pins or UART connection and set the initial program state.
KEYS = {
0xE1: "1", 0xE2: "2", 0xE3: "3",
0xE4: "4", 0xE5: "5", 0xE6: "6",
0xE7: "7", 0xE8: "8", 0xE9: "9",
0xEA: "*", 0xEB: "0", 0xEC: "#",
}
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
uart = busio.UART(
tx=board.GP20,
rx=board.GP21,
baudrate=9600,
timeout=0.01,
)
entry = ""
oled.fill(0)
oled.text("\n".join((
'Cap. Keypad',
'TX GP20 / RX GP21',
'Enter up to 6 digits',
'* clear / # submit'
)), 0, 0, 1, size=1)
oled.show()
3. Main loop Read input changes, interpret them, and update the displayed result.
try:
while True:
data = uart.read(1)
if data:
key = KEYS.get(data[0])
if key is None:
print("Ignored raw byte: 0x{:02X}".format(data[0]))
continue
if key.isdigit():
if len(entry) < 6:
entry += key
elif key == "*":
entry = ""
elif key == "#" and entry:
print("Submitted number:", entry)
entry = ""
oled.fill(0)
oled.text("\n".join((
'Cap. Keypad',
'Last key: ' + key,
'Entry: ' + (entry or '(empty)'),
'Digits: {}/6'.format(len(entry))
)), 0, 0, 1, size=1)
oled.show()
print("Key:", key, "Entry:", entry)
else:
time.sleep(0.01)
4. Cleanup Release the input, UART, and I²C resources when the program stops.
finally:
uart.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
KEYS = {
0xE1: "1", 0xE2: "2", 0xE3: "3",
0xE4: "4", 0xE5: "5", 0xE6: "6",
0xE7: "7", 0xE8: "8", 0xE9: "9",
0xEA: "*", 0xEB: "0", 0xEC: "#",
}
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
uart = busio.UART(
tx=board.GP20,
rx=board.GP21,
baudrate=9600,
timeout=0.01,
)
entry = ""
oled.fill(0)
oled.text("\n".join((
'Cap. Keypad',
'TX GP20 / RX GP21',
'Enter up to 6 digits',
'* clear / # submit'
)), 0, 0, 1, size=1)
oled.show()
# === 3. MAIN LOOP ===
try:
while True:
data = uart.read(1)
if data:
key = KEYS.get(data[0])
if key is None:
print("Ignored raw byte: 0x{:02X}".format(data[0]))
continue
if key.isdigit():
if len(entry) < 6:
entry += key
elif key == "*":
entry = ""
elif key == "#" and entry:
print("Submitted number:", entry)
entry = ""
oled.fill(0)
oled.text("\n".join((
'Cap. Keypad',
'Last key: ' + key,
'Entry: ' + (entry or '(empty)'),
'Digits: {}/6'.format(len(entry))
)), 0, 0, 1, size=1)
oled.show()
print("Key:", key, "Entry:", entry)
else:
time.sleep(0.01)
# === 4. CLEANUP ===
finally:
uart.deinit()
i2c.deinit()
Expected result Expected result: each touched key appears on the OLED and serial console. The example retains up to six numeric digits, clears them with *, and prints a submitted number when # is pressed.
Practice Test all twelve keys and compare received byte values with the key map. Change the history or entry display while keeping the keypad decoding correct.
Assignment B Accept a numeric entry of up to six digits. Press * to clear the entry. Press # to submit and display the entered number, then clear it for the next entry. Ignore # when the entry is empty, and do not accept more than six digits. Demonstrate entry, clear, and submit behavior. Save your program as LAB3_partB.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
6. Troubleshooting Symptom Check / action Button state appears reversed Remember that the buttons are active-low. With Pull.UP, True means released and False means pressed. Button action repeats unexpectedly Check that the program detects a press edge and updates the previous-state variable on every loop. No keypad bytes are received Check crossed TX/RX wiring, GP20/GP21, 9600 baud, selector configuration, power, and ground. Keypad displays the wrong key Print the raw byte in hexadecimal and compare it with the KEYS dictionary.
7. Assignment submission checklist Submit LAB3_partA.py and LAB3_partB.py through the e-learning system using the relevant submission link. Follow the deadline stated in that link. Put your name and matric number in a comment at the top of each file. Demonstrate the required button events and keypad entry, clear, and submit behavior. Explain how the electrical input state or received UART code becomes a program action. 3.4.1 Push button · 3.4.2 Keypad / UART input
LABORATORY PRACTICAL 4
Analog Input Student lab manual · EDU PICO / RP2040 · CircuitPython · Parts A–B
Measure temperature with the AHT20 and voltage with the GP28 potentiometer. The AHT20 communicates digitally over I²C, while the potentiometer voltage is sampled by the RP2040 ADC. Complete each part and its assignment before proceeding to the next.
1. Learning outcomes Read and display temperature and humidity measurements from the AHT20. Read the potentiometer through the ADC and convert the raw value into voltage and percentage. Use measurement thresholds to classify sensor values and explain the difference between digital sensor data and analogue voltage sampling. Run, explain, modify, and safely stop measurement programs. 2. Equipment and preparation EDU PICO with RP2040, USB data cable, computer with Thonny, and compatible CircuitPython firmware. AHT20 temperature/humidity sensor on the shared I²C bus: SDA GP4 and SCL GP5. Onboard potentiometer connected to GP28 / ADC2. The EDU PICO OLED also uses the shared I²C bus. Install the Adafruit AHTX0 CircuitPython library and its matching dependencies in CIRCUITPY/lib. Use the course EDU PICO helper library for the OLED. 3. Measurement concepts The AHT20 performs measurement and conversion inside the sensor, then sends digital data over I²C. Its temperature value is read in degrees Celsius through the driver. The potentiometer forms a variable voltage. The RP2040 ADC converts that voltage to a reading exposed by CircuitPython from 0 to 65535; this API scale does not mean the physical converter has 16-bit accuracy. For the course estimate, calculate voltage = raw × 3.3 / 65535 and percentage = raw × 100 / 65535. Small endpoint or noise differences are normal. 4. Save and run your work Create a LAB4 folder. Keep guided examples separate from the assignment programs. Run one complete program at a time in Thonny. Stop it before changing hardware or starting another program that uses I²C. If a library import fails, check the firmware-compatible library bundle and confirm the files are in CIRCUITPY/lib. 5. Practical parts and assignments Part A — Temperature sensor — AHT20 The AHT20 communicates over I²C on SDA GP4 and SCL GP5. The sensor returns digital measurements through its driver; this is not an ADC voltage reading. It shares the EDU PICO I²C bus with the OLED.
Guided example Study the example section by section. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and sensor/display drivers used by this program.
import time
import board
import busio
import adafruit_ahtx0
import adafruit_ssd1306
2. Initialization Create the shared I²C bus and sensor, or configure the analogue input before taking readings.
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
sensor = adafruit_ahtx0.AHTx0(i2c)
3. Main loop Acquire a new measurement, convert or format it, and show the result at a suitable interval.
try:
while True:
temperature = sensor.temperature
humidity = sensor.relative_humidity
oled.fill(0)
oled.text("\n".join((
'AHT20',
'SDA GP4 / SCL GP5',
'Temp: {:.2f} C'.format(temperature),
'Humidity: {:.1f}%'.format(humidity)
)), 0, 0, 1, size=1)
oled.show()
print("Temperature: {:.2f} C, Humidity: {:.1f}%".format(
temperature, humidity
))
time.sleep(2)
4. Cleanup Release the sensor interface or ADC input and other hardware resources when the program stops.
finally:
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import busio
import adafruit_ahtx0
import adafruit_ssd1306
# === 2. INITIALIZATION ===
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
sensor = adafruit_ahtx0.AHTx0(i2c)
# === 3. MAIN LOOP ===
try:
while True:
temperature = sensor.temperature
humidity = sensor.relative_humidity
oled.fill(0)
oled.text("\n".join((
'AHT20',
'SDA GP4 / SCL GP5',
'Temp: {:.2f} C'.format(temperature),
'Humidity: {:.1f}%'.format(humidity)
)), 0, 0, 1, size=1)
oled.show()
print("Temperature: {:.2f} C, Humidity: {:.1f}%".format(
temperature, humidity
))
time.sleep(2)
# === 4. CLEANUP ===
finally:
i2c.deinit()
Expected result Expected result: temperature in degrees Celsius and relative humidity appear on the OLED and serial console and refresh every two seconds.
Practice Compare temperature and humidity readings at two different safe conditions. Explain why the AHT20 reading is digital over I²C rather than a voltage read with analogio.
Assignment A Read and display temperature to two decimal places every 2 seconds. Display NORMAL below 30.00 °C and WARNING at or above 30.00 °C. Print both the temperature and status to the serial console. Demonstrate the program and explain the threshold comparison. Save your program as LAB4_partA.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
Part B — Potentiometer — ADC input The potentiometer wiper connects to GP28 / ADC2. CircuitPython exposes the reading on a 0–65535 scale. Estimate voltage using raw × 3.3 / 65535 and position using raw × 100 / 65535.
Guided example Study the example section by section. The excerpts belong to one program; preserve indentation and use the complete listing when copying into Thonny.
1. Imports Load the modules and sensor/display drivers used by this program.
import time
import board
import analogio
import busio
import adafruit_ssd1306
2. Initialization Create the shared I²C bus and sensor, or configure the analogue input before taking readings.
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
potentiometer = analogio.AnalogIn(board.GP28)
3. Main loop Acquire a new measurement, convert or format it, and show the result at a suitable interval.
try:
while True:
raw = potentiometer.value
voltage = raw * 3.3 / 65535
percentage = raw * 100 / 65535
oled.fill(0)
oled.text("\n".join((
'Potentiometer',
'Input: GP28',
'Voltage: {:.2f} V'.format(voltage),
'Position: {:.0f}%'.format(percentage)
)), 0, 0, 1, size=1)
oled.show()
print("ADC: {}, voltage: {:.2f} V, position: {:.1f}%".format(
raw, voltage, percentage
))
time.sleep(0.2)
4. Cleanup Release the sensor interface or ADC input and other hardware resources when the program stops.
finally:
potentiometer.deinit()
i2c.deinit()
Complete runnable program — copy all sections together # === 1. IMPORTS ===
import time
import board
import analogio
import busio
import adafruit_ssd1306
# === 2. INITIALIZATION ===
i2c = busio.I2C(board.GP5, board.GP4) # SCL, SDA
oled = adafruit_ssd1306.SSD1306_I2C(128, 64, i2c)
potentiometer = analogio.AnalogIn(board.GP28)
# === 3. MAIN LOOP ===
try:
while True:
raw = potentiometer.value
voltage = raw * 3.3 / 65535
percentage = raw * 100 / 65535
oled.fill(0)
oled.text("\n".join((
'Potentiometer',
'Input: GP28',
'Voltage: {:.2f} V'.format(voltage),
'Position: {:.0f}%'.format(percentage)
)), 0, 0, 1, size=1)
oled.show()
print("ADC: {}, voltage: {:.2f} V, position: {:.1f}%".format(
raw, voltage, percentage
))
time.sleep(0.2)
# === 4. CLEANUP ===
finally:
potentiometer.deinit()
i2c.deinit()
Expected result Expected result: turning the potentiometer changes its ADC reading, calculated voltage, and percentage. The OLED and serial console update every 0.2 seconds.
Practice Turn the potentiometer slowly from one end to the other. Compare the raw, voltage, and percentage values and explain why the displayed values may not reach exactly 0 or 100%.
Assignment B Read the potentiometer every 0.2 seconds and display its ADC value, voltage, percentage, and level. Use these fixed levels: LOW below 33%; MID from 33% to below 67%; HIGH at or above 67%. Demonstrate the low, middle, and high ranges. Save your program as LAB4_partB.py and submit it through the e-learning system using the relevant submission link. Follow the deadline stated in that link.
6. Troubleshooting Symptom Check / action AHT20 import fails Install the matching adafruit_ahtx0 library and required dependencies, then restart the board. AHT20 is not detected or readings fail Check shared I²C SDA GP4 / SCL GP5, sensor power, and that the OLED and AHT20 use the same bus object. Potentiometer value does not change Confirm the potentiometer input is GP28 / ADC2 and that the AnalogIn object is read inside the loop. Calculated voltage or percentage seems incorrect Use the 0–65535 CircuitPython scale and the 3.3 V reference in the stated conversion formulas.
7. Assignment submission checklist Submit LAB4_partA.py and LAB4_partB.py through the e-learning system using the relevant submission link. Follow the deadline stated in that link. Put your name and matric number in a comment at the top of each file. Demonstrate the temperature threshold status and the LOW, MID, and HIGH potentiometer ranges. Explain how the AHT20 measurement differs from the potentiometer ADC reading. 3.3.2 Temperature sensor · 3.3.3 Potentiometer / ADC · 3.4 I²C sensors