RP2040 + CIRCUITPYTHON
English · offline

LECTURE NOTE · SESSION 2026/2027

Embedded systems.
Built on RP2040.

EDI4153 Embedded System · Faculty of Ocean Engineering Technology · Year 3, Semester 1 · 3(2+1) credits.

ABOUT THIS COURSE

Course synopsis

This course is useful for students to understand how an embedded system work, starting from introduction to main components in an embedded system. Then, the detail function of each component in embedded system and how to program it are discussed further in separate topics. Started with the simplest component which is a system output, followed by a system input, software components and hardware components. This course also provides practical slots to enhance programming skills for different types of input and output devices that commonly used in embedded system.

WHAT YOU WILL ACHIEVE

Course learning outcomes

At the end of the course, student should be able to:

CLO1

Determine the correct concepts of hardware and software components in solving a given problem of embedded system.

(C4, PLO2)

CLO2

Build executable programs using input and output devices to produce an embedded system, integrating problem-solving competency.

(P4, PLO 3)-SC 6

CLO3

Propose a marketable product of an embedded system from the hardware provided, demonstrating normative competency in decision-making and product development.

(A3, PLO 10)-SC 8

Source: EDI4153 Embedded System Syllabus v1.1 · 23 February 2026 · Page 1 ↗
Synopsis and CLO wording reproduced from the supplied syllabus.

Your chapters

05 CHAPTERS / 45 TOPICS
RP2040Microcontroller
EDU PICOLearning platform
CircuitPythonProgramming language
ThonnyDevelopment environment

CHAPTER 01

Introduction to Embedded Systems

YOUR LEARNING GOALS

Chapter 1 learning outcomes

By the end of this chapter, students should be able to:

  1. Explain the characteristics of an embedded system and identify its inputs, processing, outputs, hardware, and software in a real application.
  2. Distinguish the RP2040 microcontroller, Raspberry Pi Pico W controller board, and EDU PICO learning platform, and identify their roles in a complete system.
  3. Identify the functions of power, ground, reset, clock, and GPIO connections, and select suitable interfaces for EDU PICO devices.
  4. Develop an algorithm and flowchart for a simple embedded-system task.
  5. Use Thonny to prepare CircuitPython, save and execute code.py, and diagnose basic syntax, runtime, and logical errors.

Select a subtopic to view its planned coverage.

CHAPTER 1 / SUBTOPIC 1.1

1.1 Embedded systems

Understand the complete system before you program its parts.

Read → analyse → calculate → predict → justify

START HERE

What you should be able to do

  • Explain an embedded system using its purpose, physical interactions, and hardware/software relationship.
  • Analyse an application by separating input devices, input information, processing, output commands, and physical effects.
  • Select and justify basic components for a stated need.
  • Calculate sampling frequency, a simplified response-time bound, and an illustrative power/energy budget with correct units.
  • Trace a decision rule and justify a simple product choice using user needs and responsible design criteria.
Syllabus outcomeRole of this lessonEvidence to collect
CLO1 · C4 · PLO2Primary: analyse system components and justify a solution.Annotated block diagram, boundary-condition explanation, and worked calculations.
CLO2 · P4 · PLO3 · SC6Foundation: predict behaviour and exercise executable decision logic.Prediction/run comparison here; later hardware programming and lab demonstration are still needed.
CLO3 · A3 · PLO10 · SC8Development: identify a user need and justify an initial product decision.Reasoned design brief here; a developed marketable-product proposal and assessment follow later.

This lesson begins the CLO journey. A quiz score or correct calculation alone does not demonstrate practical programming competency or attainment of the product-development outcome.

01 / THE IDEA

1.1.1 What is an embedded system?

An embedded system combines computing hardware and software to perform a defined role within a device or process. It receives information, processes it according to programmed rules, and may produce an indication, a communication message, or a physical action. A temperature monitor measures and displays; a temperature controller also commands an actuator to influence the process.

How hardware, software, input, and output work together

These four ideas describe one system from different viewpoints: hardware is the physical equipment; software is the set of instructions that gives the equipment its behaviour; input is information entering the controller; and output is information or a command leaving it. Input and output are named from the controller’s perspective.

ConceptWhat it meansTemperature-controller example
HardwareThe tangible electronic parts: processor, memory, sensors, switches, interfaces, power circuitry, displays, and actuator drivers.RP2040 board, temperature sensor, OLED, and motor driver.
SoftwareInstructions stored and executed by the controller. Software reads inputs, applies rules, and requests outputs; it cannot act without suitable hardware.Read the temperature, compare it with a threshold, update the display, and decide whether to switch the fan on.
InputA measured value or user command entering the system through an input device and interface. A sensor is hardware; the reading it supplies is input data.The sensor supplies 31.2 °C; a button press could select automatic or manual mode.
OutputInformation or a command produced by the program and delivered through an output interface. A display or actuator is hardware; the displayed message or control command is the output.Show “31.2 °C” on the OLED and issue a fan ON command through the motor driver.

Put together: input hardware provides data → software running on the controller processes it → output hardware presents information or causes an action. The software decision is not itself the physical action; the output circuit and device make that action possible.

The defining question is “What role does the computing system serve?” A washing-machine controller manages a washing process. It may offer several cycles, detect faults, and display messages while still serving that dedicated role. A general-purpose laptop lets its user choose many unrelated applications. The distinction is purpose and integration, not simply size, cost, or speed. See the computing/physical-process perspective in Lee and Seshia’s textbook.

Illustrations of a washing machine, microwave oven, and automatic doorWashing machineSequence + level sensingMicrowave ovenUser setting + timed operationAutomatic doorDetection + movement
Figure 1.0. Original schematic illustrations of familiar applications. Students should identify a specific controller within each product; the drawings do not represent circuit wiring.
CharacteristicMeaningExample / limit
Defined purposeDesigned around a particular application and its requirements.A washer can wash, rinse, and spin; “dedicated” does not mean one instruction or one mode.
Hardware + softwareElectronics provide capabilities; the program selects behaviour.A motor driver can switch a motor, but software determines when.
Physical interactionSensors, human inputs, and actuators connect computation to the world.A button press requests an action; a sensor measures a condition.
Timing requirementsSome results are useful only if produced before a required deadline.An alarm that arrives too late may be ineffective; real-time does not simply mean “fast”.
Resource constraintsPower, memory, cost, size, and processing time affect design.Battery-powered products must budget energy as well as compute time.
Reliability and usabilityThe system must behave predictably and communicate its state.A visible fault message is different from silently reporting a normal reading.

11 / CHIP OR COMPLETE COMPUTER?

1.1.2 Microcontroller and microcomputer: compare the scope

A microcontroller (MCU) is an integrated circuit designed to control devices. It contains a processor core, on-chip memory, and control peripherals such as GPIO and timers. The RP2040 is the microcontroller chip used on the Raspberry Pi Pico W.

A microcomputer is a complete small computer system. It combines a processor with memory, storage, input/output connections, power, and other support needed to run programs. A Raspberry Pi computer is one familiar example. These computers often run an operating system and many applications; some are also used inside embedded products.

Microcontroller chipProcessor core(s) + on-chip memory + control peripheralsExample: RP2040
Microcontroller boardChip + supporting circuitry + user connectionsExample: Raspberry Pi Pico W
Microcomputer / SBCComplete computer system with processor, memory, storage, I/O, and software environmentExample: Raspberry Pi computer
Comparison aspectMicrocontrollerMicrocomputer
ScopeUsually one integrated control chip.A complete small computer system or platform.
Hardware integrationProcessor core(s), on-chip memory, and control peripherals are integrated; details vary.A processor or SoC works with system memory, storage, I/O, and supporting components. These may be integrated or placed on the board.
Typical program environmentFirmware or a lightweight runtime controls a defined application.Often an operating system and multiple applications, though this is not a strict rule.
ExamplesThe RP2040 chip is a microcontroller.A Raspberry Pi computer is a complete computer board; Pico W is a microcontroller board based on the RP2040.

Quick classification check

Identify each item as a microcontroller chip, microcontroller board, or microcomputer: RP2040; Raspberry Pi Pico W; Raspberry Pi computer.

Reveal answer and reasoning

RP2040 is the microcontroller chip. Pico W is a microcontroller board built around the RP2040. A Raspberry Pi computer is a complete computer board. These items describe different layers, so state whether you mean the chip, the board, or the complete computer system.

Sources: Pico W datasheet; Raspberry Pi documentation for Pico microcontroller boards and Raspberry Pi computers and single-board computers.

02 / CLASSIFY AND JUSTIFY

1.1.3 Embedded and general-purpose computing

Comparison dimensionGeneral-purpose laptopWashing-machine controller
User controlThe user installs and runs many applications.The user chooses among designed washing functions.
Connected devicesGeneral peripherals and optional accessories.Controls and devices associated with the washing process.
Success criteriaDepends on the chosen application.Correct sequence, user interaction, and required process behaviour.
Effect of failureDepends on the task and user context.A wrong action can disrupt the physical washing process.

A product can contain both kinds of computing. A car may have an application-rich infotainment system and several dedicated controllers. Analyse the subsystem you are asked about rather than assigning one label to every part of a complex product.

Discuss: is a development board already a finished embedded product?

A student places an unprogrammed EDU PICO on a desk. Has the student built a useful temperature controller? Explain.

Reveal answer and reasoning

No. The board supplies hardware capabilities, but a defined application needs an appropriate program, configured interfaces, a power arrangement, and verification against requirements. A development board can become the computing platform within the proposed product.

03 / COMPONENTS AND SIGNALS

1.1.4 Follow the information, then the physical action

Closed-loop system: environment to input, controller, output driver and physical response; memory and software support processingINPUTSensor / user commandPROCESSController + programOUTPUTDriver + actuatorMEMORYInstructions + working dataPhysical process changes → sensor measures againMeasured informationCommand → physical effect
Figure 1.1. Conceptual feedback system. Arrows represent information and influence, not a wiring diagram. Some applications only monitor a process; they need not close a control loop.
ElementFunctionTemperature-controller example
Input deviceDetect a physical quantity or receive a user action.AHT20 sensor; a button could request a mode change.
Input informationThe value or state delivered to the program.Temperature = 31.2 °C; button pressed = true.
Processor / controllerExecute instructions and coordinate operations.RP2040 executes the software stack.
ProgramDescribe acquisition, decisions, sequencing, and output commands.Compare measured temperature with a threshold.
MemoryHold stored code and temporary working data.Stored program; current reading and fan-command state.
Interface / driverTransfer data or provide suitable electrical drive.I²C interface for the sensor; motor driver for the fan motor.
Output devicePresent information or produce a physical effect.OLED; motor with an attached fan.
System outputThe information or command produced.Displayed “31.2 °C”; fan command ON.
Power and supportProvide energy and conditions for operation.Board supply, regulation, clock, and reset.

Device ≠ information. “AHT20” names a device; “31.2 °C” is information. “Motor” names hardware; “fan ON command” is a system output. Airflow is the resulting physical effect. A command is not proof that the motor actually moved: verification needs observation or a suitable feedback sensor.

In a sensor chain, a physical quantity is transduced into an electrical representation. Conditioning may scale or filter it. Analogue signals may require ADC conversion. A digital sensor can perform conversion internally and send numerical data through an interface. These blocks may be inside one device rather than separate visible components.

Short check: separate device, data, command, and effect

Classify: push button; 28.4 °C; RP2040; fan ON; rotating shaft; OLED.

Reveal answer and reasoning

Push button: input device. 28.4 °C: input data. RP2040: processing hardware. Fan ON: output command. Rotating shaft: physical effect. OLED: output device. A complete answer explains the role in the specified application.

04 / YOUR TEACHING PLATFORM

1.1.5 Recognise the devices on EDU PICO

EDU PICO board with numbered component locations corresponding to the adjacent legend.
  1. Pico W controller board. Contains the RP2040 chip; this is the processing platform.
  2. AHT20 module. Digital temperature/humidity input.
  3. Buttons A and B. User inputs.
  4. OLED. Visual information output.
  5. Piezo buzzer. Audible output.
  6. RGB LEDs. Colour/status outputs.
  7. Motor outputs and driver area. Connect a suitable external motor; the motor is not built into the PCB.
Figure 1.2. EDU PICO board illustration extracted from the lecturer-supplied Cytron “Explore STEM and Coding with EDU PICO”, page 12. Numbered overlays and legend added for this lesson. Illustration © Cytron Technologies; connector details are taught in 1.2.

RP2040 is the chip; Pico W is the board containing that chip; EDU PICO is the learning platform with additional devices and connections. A board GPIO connection is not the same as a chip package pin number. We will examine the actual connections in 1.2. The chip/board relationship is documented in Raspberry Pi’s Pico documentation.

For this lesson, recognise the components and their roles. A DC motor/fan or servo is a connected accessory. The TM1650 four-digit display in 2.6 is an extension module. Identifying these boundaries prevents an incorrect parts list when planning a product.

Application rule and CircuitPython runtime control RP2040 hardware and physical devicesAPPLICATIONRead → decide → commandCIRCUITPYTHONRuntime + device driversHARDWARERP2040 + connected I/OA change in the decision rule changes behaviour, even when the hardware stays the same.
Figure 1.3. Software and hardware relationship. The RP2040 executes machine instructions in the runtime and drivers that support the student’s CircuitPython application.

Suppose the same temperature sensor and fan are retained. Program A turns the fan on at 30 °C, while Program B turns it on at 35 °C. The components have not changed, but the specified behaviour has. Software therefore forms part of the engineering solution, rather than being an optional addition to the circuit.

05 / WORKED SYSTEM ANALYSIS

1.1.6 A temperature monitor with automatic ventilation

Problem: a small equipment enclosure needs a visible temperature indication and automatic fan operation above a chosen threshold. This is an educational prototype, adapted from the sensor-and-actuator approach in the supplied EDU PICO greenhouse project; it is not a validated protection system.

Teaching assumptions: readings are valid; the driver and motor are connected correctly; the fan command is either ON or OFF; and the illustrative threshold is 30.0 °C. That number is a classroom design parameter, not a universal safe equipment temperature.

RequirementSelected elementReason
Read enclosure temperatureAHT20Measures the required physical quantity.
Apply a defined ruleRP2040 + CircuitPythonAcquires the value and evaluates the comparison.
Show current informationOLEDDisplays a number and the requested operating state.
Command ventilationMotor driver + connected motor/fanProvides physical movement using an appropriate power path.
Operate repeatedlyRepeating acquisition–decision–output sequenceRe-evaluates the command when the measured condition changes.

The simplified rule is: if T ≥ 30.0 °C, command the fan ON; otherwise command it OFF. Display T and the command each cycle. Initialization sets the command OFF until the first decision. The model assumes successful reads; sensor-fault handling must be specified when building a practical system.

Control loop: initialise outputs off, read temperature, test T greater than or equal to 30 degrees, command fan on or off, update OLED, wait and repeatStart / resetInitialize sensor, display and driverInitial fan command: OFFRead temperature T (°C)T ≥ 30 °C?NO: T < 30YES: T ≥ 30Fan command: OFFFan command: ONUpdate OLED: temperatureand fan commandWait / pace the next iterationRepeat while powered
Figure 1.4. Original flowchart for the stated valid-reading model. The rounded terminal marks the start, rectangles mark processes, parallelograms mark I/O, and the diamond marks a decision. The loop returns to a new reading.
Input TIs T ≥ 30.0?Fan commandReason
29.9 °CNoOFFBelow threshold.
30.0 °CYesONEquality is included by ≥.
30.1 °CYesONAbove threshold.
29.8 °C after 30.1 °CNoOFFThis simple rule has no retained hysteresis state.

INTERACTIVE MODEL · NO HARDWARE CONNECTED

Predict, then move the temperature slider

SIMULATED OLED25.0 °CFan command: OFF

25.0 ≥ 30.0 → False

OFF

This indicates a requested output, not measured fan motion.

At exactly 30.0 °C the command is ON. The model assumes a valid measurement and a functioning output path.

06 / ENGINEERING CALCULATIONS

1.1.7 Turn a description into quantities

An engineering answer needs a formula, substituted values, units, and interpretation. The examples below use deliberately stated classroom assumptions. They do not claim measured EDU PICO performance or replace later ADC, PWM, and timer calculations.

Worked example 1 — Sampling interval and sample count

A controller starts one reading every 250 ms. Find the sampling frequency and number of readings during 10 seconds, starting at t = 0 and excluding t = 10 s.

Ts
sampling interval (s)
fs
sampling frequency (samples/s)
Ns
number of samples
t
elapsed time or duration (s unless otherwise stated)
Ts = 250 msTs = 0.250 sfs = 1 ÷ Tsfs = 1 ÷ 0.250 sfs = 4 samples/sNs = t ÷ TsNs = 10 s ÷ 0.250 sNs = 40

The reading times are 0, 0.25, …, 9.75 s. Including the reading at exactly 10 s would produce 41 readings. Always specify the endpoints. A 4 Hz sampling frequency is not a 4 Hz processor clock, and a faster sample rate does not automatically improve sensor accuracy.

Worked example 2 — Worst-case command response

Assume a scheduler starts acquisitions exactly every 200 ms. After a start, sensing/transfer takes at most 20 ms, decision processing 2 ms, and issuing the driver command 3 ms. Ignore sensor internal response lag and assume these stages run sequentially without other delays. Estimate a conservative worst-case command-response bound after the real temperature crosses the threshold.

tresponse
command-response upper bound
twait
maximum scheduling wait (s or ms as stated)
tacq
acquisition time
tproc
processing time
tcmd
command issue time
tresponse ≤ twait + tacq + tproc + tcmdtresponse ≤ 200 ms + 20 ms + 2 ms + 3 mstresponse ≤ 225 ms

The event may occur just after an acquisition opportunity, so the scheduling wait can approach one interval. If the requirement is a command within 250 ms, the model has 250 − 225 = 25 ms margin. If the interval becomes 500 ms, the bound becomes 525 ms and fails that requirement.

This bounds the electrical command, not fan spin-up or cooling time. A real design must include relevant sensor latency and verify the assumed execution bounds. A simple loop that performs 25 ms of work and then sleeps for 200 ms has a roughly 225 ms start-to-start interval; it is not the fixed 200 ms schedule assumed above.

Worked example 3 — Illustrative energy budget

For a hypothetical prototype supplied at 5 V, assume the electronics draw 80 mA and the fan draws an additional 120 mA when ON. The fan is ON for 25% of a one-hour operating period. These are supplied exercise values, not measured EDU PICO specifications.

Ibase
constant base-load current (A)
Iload
additional current while the switched load is ON (A)
d
fraction of the observation interval with the load ON (0–1); not PWM duty here
Iavg
average supply current (A)
V
voltage (V)
Pavg
average power (W)
E
energy (Wh when power is W and time is h)
Iavg = Ibase + d × IloadIavg = 80 mA + 0.25 × 120 mAIavg = 110 mAIavg = 0.110 APavg = V × IavgPavg = 5 V × 0.110 APavg = 0.55 WE = Pavg × 1 hE = 0.55 W × 1 hE = 0.55 Wh

With an assumed usable supply energy of 2.75 Wh, ideal runtime is 2.75 / 0.55 = 5 hours. Conversion losses, startup current, battery behaviour, and other loads must be accounted for in a measured design. Here 25% means the fraction of the observation period with the fan ON; it is not the PWM waveform duty cycle taught in Chapter 2.

Explore the response-time assumption

Bound: 225 ms. Meets the 250 ms model requirement; margin 25 ms.

Fixed added work: 20 + 2 + 3 = 25 ms. This calculator uses the fixed-schedule model from worked example 2.

07 / FROM ANALYSIS TO EXECUTABLE LOGIC

Calculation tutorial — sampling and energy

Identify the given values, write the formula, substitute with consistent units, then interpret the answer.

Ts
sampling interval (s)
fs
sampling frequency (samples/s)
Ns
number of samples
t
elapsed time or duration (s unless otherwise stated)
V
voltage (V)
Iavg
average supply current (A)
Pavg
average power (W)
E
energy (Wh when power is W and time is h)
trun
ideal runtime (h)
Example 1 — Find the sampling frequency and sample count for a 125 ms interval over 6 s, excluding the final endpoint

Given: Interval 0.125 s; duration 6 s, excluding the final endpoint.

fs = 1 ÷ Tsfs = 1 ÷ 0.125 sfs = 8 samples/sNs = t ÷ TsNs = 6 s ÷ 0.125 sNs = 48

Interpretation: Including a reading exactly at 6 s would give 49 readings.

Example 2 — Find average power and ideal runtime given 5 V, 0.100 A average current and 2.5 Wh usable energy

Given: Average current 0.100 A; supply 5 V; usable energy 2.5 Wh.

Pavg = V × IavgPavg = 5 V × 0.100 APavg = 0.50 Wtrun = E ÷ Pavgtrun = 2.5 Wh ÷ 0.50 Wtrun = 5 h

Interpretation: The average current already accounts for load ON-time; conversion losses and other loads reduce runtime.

1.1.8 Predict → run → compare → explain

This small example isolates the decision rule so you can test a prediction before wiring devices. It uses a tuple of supplied temperatures instead of a sensor. It can run in the CircuitPython console or standard Python. It does not command a real motor, and it does not by itself fulfil the hardware programming requirements of CLO2.

Decision-logic exerciseDownload .py ↓
"""1.1 decision-logic exercise: simulated readings, no physical I/O.
Runs in CircuitPython's console or standard Python.
"""
threshold_c = 30.0
readings_c = (29.9, 30.0, 30.1, 29.8)

for temperature_c in readings_c:
    if temperature_c >= threshold_c:
        fan_command = "ON"
    else:
        fan_command = "OFF"
    print("T={:.1f} C | Fan command: {}".format(
        temperature_c, fan_command))

Write the expected four output lines before running. Then compare the console output with your predictions. Change >= to > and repeat. Explain why the equality case changes. Detailed Python constructs will be developed in 1.3, 2.2, and Chapter 4.

Reveal answer and reasoning
T=29.9 C | Fan command: OFF
T=30.0 C | Fan command: ON
T=30.1 C | Fan command: ON
T=29.8 C | Fan command: OFF

With >, the 30.0 °C result becomes OFF. A comparison operator expresses a precise requirement; it is not an interchangeable punctuation choice.

Problem-solving record

  • State the required rule in words.
  • Predict each output, including equality at the threshold.
  • Run the supplied logic and record discrepancies.
  • Identify whether a discrepancy comes from your prediction, the operator, or the supplied data.
  • Explain what must change to acquire a real sensor reading and issue a real output command later.

08 / EARLY PRODUCT THINKING

1.1.9 A useful device starts with a user need

CLO3 includes normative competency: decisions should consider what the product ought to do for its users and others affected by it. Technical feasibility and low component cost are not sufficient reasons to call a product marketable. State the intended user, explain the benefit, and justify trade-offs using relevant values and evidence.

Formative design brief

Propose a small equipment-room temperature indicator using the provided teaching hardware. Identify one intended user, one observable problem, the input–process–output arrangement, and two measurable acceptance criteria. Explain one choice involving reliability, accessibility, energy use, or truthful presentation of information.

DecisionQuestion to investigateEvidence or justification
Silent indicator or audible alarm?Will the user see the display? Could frequent sound cause nuisance?Explain the operating setting; consider acknowledgement and a visible persistent warning.
Reuse the teaching kit or design a smaller product?What is suitable for a prototype versus production?Identify the functions actually required; distinguish development hardware from a production bill of materials.
Show a number after sensor failure?Could a stale value mislead a user?Propose a distinct fault indication and a justified response rather than treating old data as current.
Claim “marketable”?Who would use or buy it, and what alternative do they use now?Seek user feedback and state untested assumptions. A prototype demonstration is not market validation.

Illustrative decision calculation

Suppose two hypothetical solutions meet the same functional requirement. A costs RM60 and uses 1.2 W on average; B costs RM75 and uses 0.8 W. Over 100 hours, A uses 120 Wh and B uses 80 Wh: B saves 40 Wh for RM15 additional upfront cost. This is an energy comparison, not a financial payback calculation. Payback would also need an electricity tariff and operating lifetime. Reliability and user suitability may change the decision.

Reveal answer and reasoning

A defensible brief names a user, identifies a specific problem, draws a consistent signal path, states testable criteria, and justifies a choice using evidence or explicitly labelled assumptions. For example: “Under the stated timing model, issue a fan command within 250 ms” is testable; “works very fast” is not.

09 / QUIZ PRACTICE

1.1.10 Check your conceptual understanding

Six formative questions, one mark each. Answer all questions before checking. Scores are shown only in this page; they are not recorded as formal assessment results.

1. Which description best identifies an embedded system?
2. Which pair correctly separates an input device from its information?
3. For fan ON when T ≥ 30.0 °C, what happens at exactly 30.0 °C?
4. An OLED says “Fan ON”. What has this proved?
5. Readings start every 0.5 s. What is the sampling frequency?
6. Which activity provides the strongest evidence of practical CLO2?

10 / TEST AND CALCULATION PRACTICE

1.1.11 Show your reasoning

The following are practice items with indicative marking guides. They do not change the assessment weights in the syllabus. Complete the questions before opening the answers.

Q1 · System analysis [8 marks]

An automatic door uses a presence sensor, a controller, a motor driver, a motor, and a status lamp. Identify input information, processing, output command, and physical effect. Explain why a lamp marked “OPEN” does not necessarily prove the door is physically open.

Reveal answer and reasoning

Presence state (1); interpret the state and decide movement (1); command motor driver to open/stop (1); motor moves the door (1). Distinguish sensor/controller/driver/motor roles consistently (2). The lamp can show a requested state (1), while physical position requires a limit switch, encoder, or other suitable verification (1).

Q2 · Sampling calculation [5 marks]

A controller samples every 125 ms. Calculate sampling frequency and the number of samples in 6 seconds for sampling times starting at 0 and strictly below 6 s. Explain the endpoint convention.

Reveal answer and reasoning

125 ms = 0.125 s (1). f = 1/T (1) = 8 Hz (1). N = 6/0.125 = 48 (1), at 0, 0.125, …, 5.875 s; including 6.000 s would add a 49th sample (1).

Q3 · Response-time calculation and judgement [6 marks]

Acquisitions start every 100 ms. Maximum acquisition time is 15 ms, processing takes 4 ms, and issuing a command takes 1 ms. Under the fixed-schedule, valid-reading assumptions, estimate the worst-case command response and judge whether it meets a 150 ms requirement. State one physical effect not included.

Reveal answer and reasoning

Identify scheduling wait up to one interval (1); add 100 + 15 + 4 + 1 (1); bound = 120 ms (1); meets the model requirement (1), with margin 30 ms (1). Motor acceleration, thermal response, or unmodelled sensor lag is not covered (1).

Q4 · Energy budget [6 marks]

At 5 V, electronics draw 60 mA and an actuator adds 100 mA when ON. The actuator is ON for 40% of the observation time. Find average current, average power, and ideal runtime from 2.5 Wh of usable supply energy.

Reveal answer and reasoning

Iavg = 60 + 0.4 × 100 = 100 mA (2). P = 5 × 0.100 = 0.50 W (2). Runtime = 2.5 Wh / 0.50 W = 5 hours under the stated ideal assumptions (2). The 40% value describes ON-time fraction here, not motor-speed percentage.

Q5 · Trace and diagnose the requirement [5 marks]

A specification says “fan ON at or above 30.0 °C”, but a program uses T > 30.0. State the outputs for 29.9, 30.0, and 30.1 °C. Identify the error and correct it.

Reveal answer and reasoning

OFF, OFF, ON for the given program (3). The equality boundary is implemented incorrectly: this is a logical requirement error (1). Use ≥, written >= in CircuitPython (1).

Q6 · Product decision [formative 6-point guide]

A user cannot continuously watch the OLED. Propose an additional indication using available hardware, and justify the choice. Address user benefit, a possible drawback, and a way to mitigate that drawback.

Reveal answer and reasoning

Identify the user situation (1); select a suitable available output such as the buzzer (1); explain the attention benefit (1); identify nuisance/false-alert or accessibility concerns (1); propose acknowledgement, suitable thresholds, or complementary visual information (1); explain how user feedback or a test would evaluate the decision (1). Several designs may be defensible. This develops CLO3 reasoning; it is not a complete marketable-product assessment.

Evidence checklist for revision

  • I can draw and explain an input–process–output model for an unfamiliar application.
  • I distinguish device, information, command, and observed physical effect.
  • My calculations show units, assumptions, and a final interpretation.
  • I can predict behaviour at a decision boundary and explain a mismatch.
  • I can justify a product choice with a user need and a trade-off, rather than only naming components.

11 / RECAP AND REFERENCES

Carry these ideas into 1.2

An embedded system is organised around a defined application. Hardware supplies sensing, processing, storage, communication, and output capabilities; software coordinates them. Good analysis separates devices from information, states measurable requirements, and checks whether the observed behaviour satisfies those requirements.

Purpose → input → processing → output → verification

Next: identify the RP2040, Pico W, and EDU PICO hardware connections in 1.2.

Sources and further reading

The flowchart, schematic diagrams, calculation scenarios, practice questions, and interactive models were prepared for this lesson. Numeric thresholds, timings, and current values are illustrative assumptions unless explicitly identified otherwise.

CHAPTER 1 / SUBTOPIC 1.2

1.2 Hardware of the microcontroller

Follow the hardware from the RP2040 chip to the EDU PICO devices you will use in class.

Identify → trace → connect → justify

START HERE

What you should be able to do

  • Distinguish the RP2040 microcontroller, Raspberry Pi Pico W board, and EDU PICO learning platform.
  • Identify the main system parts and explain their roles in an embedded application.
  • Explain the purpose of GPIO, power, ground, reset, and clock connections.
  • Distinguish active-high and active-low digital inputs, explain digital outputs, and describe ADC and PWM signal behaviour.
  • Identify the documented EDU PICO connections for selected input and output devices.
  • Choose a suitable signal interface and explain when a driver circuit is required.
Lesson boundary

This lesson identifies hardware and traces signals. Detailed GPIO programming, ADC calculations, PWM calculations, and serial-protocol timing are developed in later topics.

01 / FROM CHIP TO LEARNING PLATFORM

1.2.1 Three levels that work together

In this course, RP2040, Raspberry Pi Pico W, and EDU PICO name related but different parts of the teaching system.

Relationship between RP2040 chip, Raspberry Pi Pico W controller board, and EDU PICO learning platformRP2040Microcontroller chipProcessor cores · GPIOmemory interfaces · peripheralsPico WController boardRP2040 + flash + powerUSB + accessible pins + Wi-FiEDU PICOLearning platformPico W + onboard devicesconnectors + supporting circuitsThe chip is mounted on the Pico W; the Pico W is fitted to and used with the EDU PICO platform.
Figure 1.5. System relationship based on the EDU PICO booklet. “RP2040” means the chip; “Pico W” means the controller board; “EDU PICO” means the classroom learning platform.
PartWhat it isRole in our course
RP2040The microcontroller integrated circuit (chip).Executes instructions and provides processor, memory, GPIO and peripheral functions.
Raspberry Pi Pico WA controller board built around the RP2040.Provides USB, flash storage, power circuitry, accessible connections and wireless capability.
EDU PICOThe learning platform made for the Pico W with pre-connected sensors and output devices.Lets students use real input/output hardware with fewer separate wiring steps.
Computer + ThonnyThe external development equipment described by the booklet.Used to write and run CircuitPython programs, communicate over USB, and inspect the console.

The EDU PICO booklet describes the kit as an all-in-one learning tool using the Raspberry Pi Pico W microcontroller and pre-connected sensors. Do not call the whole learning platform “the RP2040 chip”: the chip is only one component within the larger system.

02 / THE RP2040 MICROCONTROLLER CHIP

1.2.2 What is inside the RP2040, and what does GPIO mean?

The RP2040 is the microcontroller chip at the centre of the Pico W. It contains two processor cores and the digital and analogue hardware used by a program. The drawing below is a simplified teaching illustration of the chip package: the RP2040 datasheet identifies the physical device as a 56-pin QFN package. It is not a board photograph or a wiring diagram.

Teaching illustration of the 56-pin RP2040 QFN chip package, GPIO functions, and analogue-capable GPIORP20402 × Arm Cortex-M0+ · memory · bus fabricGPIO · ADC · PWM · UART · I²C · SPI · PIOQFN-56 package · simplified · not to scaleGPIOGP0–GP29ADC capableGP26–GP29Chip package pins are distinct from Pico W and EDU PICO header pin numbers.Actual RP2040 microcontroller chip shown from the top and underside
Figure 1.6. Simplified teaching illustration of the RP2040 QFN-56 package alongside an actual RP2040 chip (top and underside). Chip photograph: Raspberry Pi RP2040 product page, © Raspberry Pi Ltd. The illustration is based on the RP2040 datasheet.

GPIO is a configurable signal connection

GPIO means General-Purpose Input/Output. At chip level, the RP2040 has 30 GPIO signals, labelled GP0 to GP29. A program can configure a suitable GPIO to read a digital input or control a digital output. Many GPIO pins can also connect to selected peripheral functions. A pin cannot perform every function at the same time; the hardware and program configuration determine which function is active.

RP2040 GPIO featureWhat it meansCourse connection
30 GPIO, GP0–GP29Multifunction digital input/output signals on the chip.Button A, LEDs, relay control, and communication pins use suitable GPIO connections.
Four ADC-capable GPIO: GP26–GP29These pins can route analogue voltage signals to the chip’s ADC as well as support digital functions.ADC principles and potentiometer readings are taught in Chapter 3.
Peripheral functionsGPIO functions can be assigned to digital peripherals such as UART, I²C, SPI, PWM, and PIO.Students identify the intended interface, then use the board-specific pin map.

The datasheet specifies a 12-bit, 500 ksps ADC for the RP2040. That is the chip capability; the usable input pins and analogue performance depend on the controller board and its wiring. This specification is background here; ADC resolution and measurement calculations belong in Chapter 3.

03 / THE RASPBERRY PI PICO W BOARD

1.2.3 The board exposes only some chip GPIO as user pins

The Pico W is a controller board built around the RP2040. It adds 2 MB of flash memory, a Micro-USB B port, power regulation, a 3-pin debug connection, and a 2.4 GHz wireless interface. The wireless radio is a separate CYW43439 device connected to the RP2040 over SPI.

Pico W circuit schematic

The manufacturer schematic shows how the Pico W circuit is assembled around the RP2040, including the USB and power circuits, wireless interface, debug connector, and GPIO header. Use it as a reference for understanding board-level connections; it is not a beginner wiring diagram. The complete schematic is presented on two sheets.

Sheet 1 of the Raspberry Pi Pico W Rev3 circuit schematic, showing the RP2040 and board circuitry
Figure 1.7. Sheet 1 of the Pico W Rev3 schematic (datasheet Figure 12, printed page 20).
Sheet 2 of the Raspberry Pi Pico W Rev3 circuit schematic, completing the board circuitry
Figure 1.8. Raspberry Pi Pico W Rev3 circuit schematic, sheets 1 and 2 (datasheet Figures 12–13, printed pages 20–21). Reproduced from the Raspberry Pi Pico W datasheet, Raspberry Pi Ltd.
Front and back views of the Raspberry Pi Pico W Rev3 controller board, with RP2040 chip, USB connector, wireless region, and header pins visible
Figure 1.9. Raspberry Pi Pico W Rev3 board, reproduced from the Raspberry Pi Pico W datasheet, p. 3 (Raspberry Pi Ltd.). This shows the controller board; EDU PICO adds its own devices and connections.

Chip GPIO versus Pico W header GPIO

Although the RP2040 chip has 30 GPIO, the Pico W exposes 26 multifunction GPIO on its side headers. They are GP0–GP22 and GP26–GP28. Of those exposed pins, 23 are digital-only and three (GP26, GP27, GP28) can also be ADC inputs.

Pin groupAvailability on Pico WFunction or reason
GP0–GP22Exposed on headerDigital GPIO with selected alternate peripheral functions.
GP26–GP28Exposed on header; ADC capableCan be used as digital GPIO or analogue inputs, as configured.
GP23Not exposed as user GPIOUsed internally for wireless power control.
GP24Not exposed as user GPIOUsed internally for wireless interface data/interrupt signalling.
GP25Not exposed as user GPIOUsed internally for wireless SPI chip select and associated board function.
GP29Not exposed as user GPIOUsed for wireless clock sharing and monitoring VSYS through ADC channel 3.

Why the counts differ: the RP2040 datasheet describes GPIO capability on the chip. The Pico W datasheet describes which signals the board actually brings to its headers and which it uses internally. Therefore, students should not assume all 30 chip GPIOs are available for external wiring on Pico W.

The Pico W pinout below labels the header GPIO, physical header-pin numbers, power, ground, and alternate functions. These are Pico W header pin numbers, not RP2040 QFN package pin numbers. The EDU PICO board connects selected Pico W signals to its onboard devices, so use the EDU PICO booklet’s device connection table for practical wiring.

Pico W Rev3 pinout diagram showing GPIO labels and physical header pin numbers
Figure 1.10. Pico W Rev3 header pinout. Consult the Pico W datasheet, p. 4 for the original diagram and complete pin notes.

04 / FIND THE HARDWARE

1.2.4 Read the EDU PICO board as a system

The board combines the controller with inputs, outputs, connectors and support circuitry. A device may be physically on the EDU PICO while its control logic runs inside the RP2040. Follow the board labels and the EDU PICO connection table when identifying a pin.

Lecturer photograph of the EDU PICO main board and its connected wiring and separate accessory modulesI1I2I3I4I5I6O1O2O3O4O5O6O7O8O9
Figure 1.11. EDU PICO main board and accessory modules, supplied by the lecturer (IMG_2326.HEIC). Blue markers identify inputs; orange markers identify outputs or output-driver connections. Accessories may be connected for practical activities; refer to the EDU PICO booklet for wiring details.
MarkerInput or output deviceRole and location
I1Buttons A and BUser digital inputs · onboard
I2PotentiometerAdjustable analogue input · onboard
I3PDM microphoneSound input · onboard
I4AHT20 temperature/humidity sensorEnvironmental sensor input · onboard
I5Proximity/light/gesture/colour sensorAPDS9960 digital sensor input · onboard
I63 × 4 keypadKey entry input · external accessory
O1Piezo buzzerSound output · onboard
O2OLED displayText and status output · onboard
O3RGB LEDsColour and status output · onboard
O4USB relay outputSwitches a supported USB load · board output connection
O5Stepper motorRotational output · external accessory
O6Stepper motor driverPower interface between controller and stepper motor · external accessory
O7Four-digit seven-segment displayNumerical display output · external accessory
O8DC motorRotational output · external accessory
O9Servo motorPositioning output · external accessory
Board versus pinout

A photograph helps locate parts, but it may not show hidden traces or every pin name. For wiring decisions, read the labelled board diagram and the device-specific connection table rather than guessing from physical proximity.

Input and output examples documented in the booklet

DeviceSystem roleDocumented connection / note
Button AUser input; program reads a pressed/released state.GP0 as digital input (booklet p. 30).
PotentiometerAdjustable analogue voltage input.Read through the EDU PICO analogue-input setup; detailed ADC use is in Chapter 3.
AHT20 temperature/humidity sensorDigital sensor input.Shares the I²C connection used by the OLED in the greenhouse example (pp. 164–168).
OLED displayVisual output.SSD1306 CircuitPython library example; SCL GP5, SDA GP4 (booklet pp. 48–49 and 164–167).
RGB LEDsLight output / status indication.NeoPixel example uses GP14 for five pixels (booklet pp. 164–167).
ServoPositioning actuator.PWM signal example on GP6 (booklet pp. 164–167).
DC motorRotating actuator.Driver signals M1A GP10 and M1B GP11 (booklet pp. 164–167); use the board’s motor-driver circuit.
USB relaySwitched output for a supported USB load.Relay control example on GP22 (booklet pp. 173–177).

Pin assignments above are the EDU PICO booklet’s documented examples. They describe this teaching platform’s wiring and should not be assumed to apply to unrelated Pico projects or other board revisions.

05 / GPIO AND SIGNAL PATHS

1.2.5 GPIO connects the program to electrical signals

GPIO means General-Purpose Input/Output. A GPIO connection can be configured to read a digital signal or produce a digital output. The program’s logic is executed by the RP2040; the pin is the electrical path between that logic and a circuit.

Four common signal jobs: two-state input, two-state output, analogue input, and PWM

A pin name alone does not tell you what the program senses or controls. First identify the signal behaviour, then choose the matching RP2040 peripheral and configure the board pin for it.

Digital input: active-high and active-low

A digital input is interpreted as one of two electrical logic levels: LOW or HIGH. The input needs a defined voltage when a switch is open. A pull-up resistor holds the signal HIGH; a pull-down resistor holds it LOW. Without a pull resistor, an open input can float and change unpredictably. The switch wiring determines whether the action is active-high or active-low.

Press the pictured buttons: click either switch in the diagram to simulate pressing and releasing it. The live readout below shows the GP0 logic level.

Two Raspberry Pi Pico input circuits: active-high with a pull-down resistor and active-low with a pull-up resistor, including their state tables
GPIO0 · INPUTLOW · 0 V
GPIO0 · INPUTHIGH · 3.3 V

Active-high · pull-down

Button released · GP0 reads LOW (0 V / False)

Active-low · pull-up

Button released · GP0 reads HIGH (3.3 V / True)

Figure 7. Lecturer-supplied active-high and active-low button diagram, with interactive button overlays and live GP0 state readouts added for teaching. The EDU PICO Button A follows the active-low pull-up arrangement (booklet pp. 29–30).

In CircuitPython, a pull-up input commonly uses digitalio.Pull.UP; a pull-down input uses digitalio.Pull.DOWN where supported. Check the signal’s Boolean value against the wiring and the intended event. The Pico W uses 3.3 V logic: keep external input signals within the board’s documented range and do not connect a 5 V signal directly.

Digital output: command a HIGH or LOW level

A digital output drives a pin to a logic LOW or HIGH. This can control a compatible logic input or a small indicator circuit. For an LED, include a series current-limiting resistor. A motor, relay coil, or other load that needs more current must use a suitable driver; never connect it directly to a GPIO pin.

Choose the RP2040 output level: HIGH lights the LED; LOW turns it off. The controls replace the static simulation panel in the supplied diagram.

RP2040 GP1 connected through a 330 ohm resistor to an LED and ground, with an interactive HIGH/LOW control illustration

Interactive LED Control

Set GP1 output:
LED StatusON
GP1 = HIGH (3.3 V) · LED ON
Figure 8. Lecturer-supplied GP1-to-LED diagram (digital output.png), with an interactive HIGH/LOW simulation added. Select HIGH to light the LED or LOW to turn it off. The diagram shows a series resistor and common ground; a real LED circuit requires a current-limiting resistor.

In CircuitPython, configure a digital pin as an output and set its value to True (HIGH) or False (LOW). “HIGH” describes the voltage level, not necessarily the device’s ON state: some circuits are active-low and turn on when their control pin is LOW.

ADC input: turn a changing voltage into a number

An analogue input can take many voltage values across its allowed range. The RP2040’s ADC samples that voltage and converts it into a digital number. A potentiometer is a useful example: its wiper voltage changes as the shaft turns. The ADC does not directly report a physical quantity such as temperature; a program must map the reading to a meaningful unit when the sensor requires it.

Rotate the potentiometer: drag the highlighted knob left or right, or move the slider. The wiper voltage and CircuitPython reading update together.

RP2040 Pico potentiometer divider wired between 3.3 volts and ground, with the wiper connected to GP26 ADC0
Wiper voltage1.650 V
CircuitPython AnalogIn.value32768 / 65535
RP2040 ADC equivalent (12-bit)2048 / 4095

The RP2040 ADC hardware is 12-bit. CircuitPython scales that measurement to a 16-bit AnalogIn.value; the 16-bit number is a software representation, not a 16-bit ADC conversion. This ideal divider model assumes a linear 10 kΩ potentiometer and a 3.3 V reference.

Figure 9. Lecturer-supplied potentiometer-to-GP26 (ADC0) wiring diagram (analog input.png), with an interactive rotary control and live voltage/value display added for teaching. The illustrated wiper voltage ranges from GND to 3V3; verify pin connections against the board revision before wiring.

The RP2040 ADC has 12-bit hardware resolution. CircuitPython’s analogio.AnalogIn.value presents a scaled 16-bit value from 0 to 65535, so software readings should not be mistaken for 12-bit raw counts. The board wiring determines which ADC pins are available to the user; on Pico W, GP26–GP28 are exposed on the header. Detailed conversion and calculations are developed in Chapter 3.

PWM output: control with timed digital pulses

Pulse-width modulation (PWM) repeatedly switches a digital output between LOW and HIGH. The duty cycle is the fraction of each period for which the signal is HIGH. At 0% it stays LOW; at 50% it is HIGH for half of every cycle; at 100% it stays HIGH. The signal is still a sequence of digital levels, not a true variable analogue voltage. A motor driver can respond to the pulse timing; a servo uses pulse width to represent a requested position.

Explore PWM: choose a frequency and duty cycle. The graph uses a fixed 5 ms time window, so changing frequency changes the number and spacing of pulses; the LED and motor indicators respond to duty cycle.

PWM frequency 1 kHz · period 1.00 ms
Duty cycle 50%
Interactive PWM waveform with selectable frequencyA waveform showing PWM pulses in a fixed 5 millisecond window, with frequency and duty cycle selected by controls.HIGHLOWtime → · fixed 5 ms window
LED brightness50% (illustrative)
Motor drive50% duty · illustrative speed response

This is a model: average LED brightness and motor speed depend on the device, driver, supply, load, and PWM frequency. A motor must be connected through a suitable driver, not directly to a GPIO pin.

Figure 10. Interactive PWM model. Select a frequency to change pulse spacing and number within the fixed 5 ms graph window; adjust duty cycle to change each pulse’s HIGH time. LED and motor responses are illustrative, not a physical measurement.

From the external crystal to the PWM signal: the Pico W’s 12 MHz crystal provides the RP2040 with a stable reference clock. The chip’s system PLL (phase-locked loop) synthesizes the system clock, clk_sys, from that reference. The PWM slices then count from clk_sys, after a programmable divider.

From the 12 MHz crystal to the system clock and PWM

The Pico W’s 12 MHz crystal gives the RP2040 a steady reference. The PLL uses that reference to create the faster clock needed by the processor and peripherals. Its VCO (voltage-controlled oscillator) is the PLL’s internal clock generator.

  1. Find the PLL reference frequency — REF_DIV. The crystal frequency is already known: fXOSC = 12 MHz. Divide it by REF_DIV to find the frequency entering the PLL. The standard setup uses REF_DIV = 1. This setting can range from 1 to 63 (0 is undefined); the PLL input must be at least 5 MHz, so a 12 MHz crystal allows REF_DIV = 1 or 2.
    fPLLref
    frequency at the PLL reference input (Hz)
    REFDIV
    PLL reference divider (dimensionless)
    fXOSC
    external crystal frequency (Hz)
    fPLLref = fXOSC ÷ REFDIV= 12 MHz ÷ 1= 12 MHz
  2. PLL multiplication — FBDIV. FBDIV can be set from 16 to 320. For this standard 125 MHz clock example, use FBDIV = 125. This is the selected divider setting for this calculation, not a frequency from the crystal.
    fPLLref
    frequency at the PLL reference input (Hz)
    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    FBDIV
    PLL feedback multiplier (dimensionless)
    fVCO = fPLLref × FBDIV= 12 MHz × 125= 1500 MHz
    The VCO must remain within 750–1600 MHz.
  3. System clock — POSTDIV1 and POSTDIV2. Each post-divider is 1 to 7. The two values must multiply to 12 to convert 1500 MHz to 125 MHz. The standard setup uses 6 and 2; 4 and 3 would also multiply to 12. When the values differ, Raspberry Pi recommends placing the larger value in POSTDIV1 for lower power consumption.
    POSTDIV1
    first PLL post-divider (dimensionless)
    POSTDIV2
    second PLL post-divider (dimensionless)
    fsys
    system-clock frequency (Hz)
    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    fsys = fVCO ÷ (POSTDIV1 × POSTDIV2)= 1500 MHz ÷ (6 × 2)= 1500 MHz ÷ 12= 125 MHz
    So, for this standard setup, the RP2040 system clock (clk_sys) is 125 MHz. Other clock configurations may use different values.
  4. PWM frequency. The PWM counter uses clk_sys. In edge-aligned mode:
    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)]
    D is the PWM clock divider. TOP is the 16-bit counter limit (0–65,535); the counter counts from 0 through TOP, so each period has TOP + 1 counts. The value 6249 is chosen to produce the target frequency of 20 kHz when D = 1. Rearrange the formula to calculate TOP:
    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= 125,000,000 ÷ (1 × 20,000) − 1= 6250 − 1= 6249
    Check the result in the original formula:
    fPWM
    PWM output frequency (Hz)
    fPWM = 125,000,000 ÷ [1 × (6249 + 1)]= 125,000,000 ÷ 6250= 20,000 Hz= 20 kHz
    6249 is not the only possible TOP value; a different TOP or divider produces a different PWM frequency.

Clock path: 12 MHz crystal → PLL VCO at 1500 MHz → clk_sys at 125 MHz → PWM counter → PWM output. Phase-correct PWM runs at half the edge-aligned frequency with the same divider and TOP. Source: RP2040 datasheet, sections 2.18 and 4.5.

PWM resolution on the RP2040: the PWM counter and TOP setting are 16-bit, so the hardware can provide up to 16-bit duty-cycle granularity when the selected frequency allows a suitably high TOP value. Increasing PWM frequency generally lowers the counter’s TOP and reduces the number of effective duty steps. In CircuitPython, pwmio.PWMOut.duty_cycle is specified on a 16-bit scale from 0 to 65535 (for example, 32768 is approximately 50%); the library documentation notes that the underlying hardware may provide fewer effective bits. This is a digital pulse output, not a 16-bit analogue voltage. See the RP2040 datasheet, Raspberry Pi PWM hardware API, and CircuitPython PWMOut documentation. Chapter 2 develops PWM and actuator control.

Keep the four jobs distinct: a digital input reads HIGH/LOW; a digital output sets HIGH/LOW; an ADC input measures a voltage as a number; PWM output produces timed HIGH/LOW pulses. Pico W pins are multiplexed, so one pin performs the selected role at a time. Sources: RP2040 datasheet, CircuitPython digitalio, analogio, and pwmio.
Button signal enters the RP2040 through GPIO GP0; program processing controls an output through a suitable driverButton Auser inputGP0 · digital inputRP2040reads the pin stateexecutes CircuitPython logicprogram decides the responseOutput circuitLED / motor driverappropriate GPIO functionInformation flows in; the controller processes it; a suitable circuit produces an output effect.
Figure 11. Simplified signal path. This is a system diagram, not a complete electrical schematic.
TermMeaningCourse example
Digital inputController interprets a voltage as one of two logic states.Read Button A on GP0; the booklet configures it as an input with a pull-up.
Digital outputController sets a logic state for a compatible circuit.Switch an indicator circuit; output current limits still apply.
ADC inputMeasures an analogue voltage and represents it as a digital reading.Read the EDU PICO potentiometer in Chapter 3.
PWM outputProduces a repeating pulse signal whose timing can be configured.Control a servo or motor-driver input; developed in Chapter 2.
Bus pinsCarry serial communication signals to peripherals.I²C OLED and AHT20 use SCL GP5 and SDA GP4 in the booklet example.

06 / POWER, GROUND, RESET, AND CLOCK

1.2.6 Four ideas needed to understand the board

ConceptPurposeWhat to look for
PowerProvides electrical energy to the board and connected circuits.The booklet starts by connecting EDU PICO to a computer with a Micro-B USB cable and turning on its ON/OFF switch; the PWR LED lights (p. 12).
Ground (GND)Provides a shared voltage reference and part of the return path in a circuit.Follow the documented ground connection when wiring an external circuit; never infer a pin from appearance alone.
Reset (RST)Restarts the controller so startup begins again.The booklet describes pressing RST to restart the board, including after enabling its data-logging mode (p. 180).
ClockProvides timing used by processor and peripheral operations.The clock is part of the controller hardware; later Chapter 5 develops clock, timer and timing calculations.

When the computer powers the teaching setup over USB, the cable also provides the programming/communication connection used in the booklet workflow. Power and data are related through the connection but are different functions. The EDU PICO’s ON/OFF switch controls whether the board is turned on in the illustrated setup.

Shared ground: when a controller sends a signal to a separate circuit, both sides generally need a common voltage reference. Without the correct reference, the receiving circuit may not interpret the signal reliably. Always follow the hardware’s wiring instructions and power requirements.

07 / HOW DEVICES CONNECT

1.2.7 Select the interface that matches the device

InterfaceSignal ideaEDU PICO course exampleDeveloped later in
GPIOOne or more digital signal pins.Button A on GP0; USB relay example on GP22.2.4, 3.2 and 3.4
ADCMeasures an analogue voltage on a supported input.Potentiometer.3.3 and 3.3.1
PWMTimed pulse output for control signals.Servo on GP6; motor driver signals on GP10/GP11.2.8–2.12
I²CTwo shared signal lines: clock (SCL) and data (SDA); devices have addresses.OLED, AHT20 and APDS9960 use GP5 (SCL) and GP4 (SDA) in the booklet’s greenhouse example.2.7, 3.3.2 and Chapter 5
UART / SPIOther serial communication interfaces with their own signal arrangements.Introduced here as RP2040 peripheral options; no device connection is required for this lesson.Chapter 5

Several I²C devices can share the same SDA and SCL wires when the electrical arrangement is suitable and each device has a distinct address. This lets the AHT20 provide measurements while the OLED receives display data over the same bus. CircuitPython libraries simplify communication, but they do not change which physical pins are connected.

08 / WORK THROUGH THE CONNECTION

1.2.8 Worked examples

Example 1 · Button input to program decision

The EDU PICO booklet’s Button A example connects the button to GP0 as a digital input. Trace what happens when a student presses it.

  1. The physical button changes the electrical state on its input circuit.
  2. GP0 carries that digital signal to an RP2040 input function.
  3. The running CircuitPython program reads the input state and applies its decision rule.
  4. The program may print a message or command a compatible output circuit.

Why does the button not “run the program” by itself? It changes an input signal. The processor executes instructions that read and respond to that signal.

Example 2 · Sensor measurement to OLED status

In the booklet’s greenhouse example, the AHT20 sensor and SSD1306 OLED share I²C pins: GP5 for SCL and GP4 for SDA.

  1. The AHT20 measures temperature and humidity and communicates digital data over I²C.
  2. The RP2040 runs the CircuitPython program and obtains readings through the sensor library.
  3. The program decides what status to show.
  4. The OLED receives display data over the same I²C bus and presents the status to the user.

The AHT20’s reading is digitally communicated sensor data. It is not a voltage measurement made by the RP2040 ADC.

Example 3 · Why the motor uses a driver

The greenhouse example controls a DC motor through the EDU PICO motor connection using M1A (GP10) and M1B (GP11) signals.

The GPIO signals are control inputs to the motor-driver circuit. The driver handles the motor’s electrical load. The RP2040 decides the requested direction or speed, but its GPIO pins do not supply motor current directly.

09 / CHECK YOUR UNDERSTANDING

1.2.9 Practice for quizzes and tests

ActivityQuestionEvidence of understanding
ClassifySort RP2040, Pico W, EDU PICO, computer and Thonny into chip, controller board, learning platform, computer and software.Correctly distinguishes the hardware levels and development tool.
TraceDraw the path from Button A press to a program-controlled indication.Separates physical input, signal, processing, program decision and output.
ChooseChoose GPIO, ADC, PWM or I²C for a button, potentiometer, servo-control signal or OLED.Matches interface to signal/device and explains the selection.
DiagnoseA student connects a motor directly to one GPIO pin and omits the common reference between circuits. Identify the problems.Explains current/driver needs and the role of ground.
InterpretFor the OLED/AHT20 example, name SDA, SCL, and their documented GP numbers.Correctly identifies SDA=GP4 and SCL=GP5 for this EDU PICO example.
Reveal concise answer guide

Classify: RP2040 is the chip; Pico W is the controller board built around it; EDU PICO is the learning platform with pre-connected devices and supporting circuitry; the computer runs Thonny, which is development software.

Trace: button press → GP0 digital input signal → RP2040 reads it → CircuitPython program makes a decision → compatible output circuit responds.

Choose: button: GPIO input; potentiometer: ADC input; servo-control signal: PWM; OLED: I²C. The motor is driven through the board’s motor-driver circuit.

Diagnose: a GPIO pin should not supply motor current directly; use an appropriate driver. Follow the specified wiring and provide a shared ground reference where required. For the OLED/AHT20 example, GP4 is SDA and GP5 is SCL.

Assessment reminder

A correct pin number is only part of a sound answer. Students should state the device’s role, identify the signal/interface, trace where processing happens, and justify any driver or power requirement. Practical wiring and testing still provide evidence that a written quiz cannot.

1.2.10 Check your understanding: 10 MCQs

Select one answer for each question, then choose Check answers. The feedback explains the correct idea.

1. Which statement correctly distinguishes the RP2040, Pico W, and EDU PICO?
2. A digital input is used to:
3. In an active-high pushbutton circuit with a pull-down resistor, what does the input normally read?
4. For an active-low button using a pull-up resistor, the input is:
5. GP1 is connected to an LED through a suitable series resistor, with the LED returning to GND. What happens when GP1 is HIGH?
6. Which statement about the RP2040 ADC and CircuitPython reading is correct?
7. What does PWM duty cycle describe?
8. With a 12 MHz reference, what is the standard PLL_SYS calculation for 125 MHz?
9. In normal edge-aligned PWM, with clk_sys = 125 MHz, divider D = 1, and TOP = 6249, what is the frequency?
10. For a PWM period of 6250 counter ticks, approximately how many HIGH ticks give a 40% duty cycle?
Score: not checked yet

1.2.11 Calculation tutorial: ADC, clock, and PWM

Work 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 MHzfsys = 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) − 1TOP = 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 × CCHIGH ≈ 0.40 × 6250CHIGH = 2500p = (CHIGH ÷ C) × 100p = (2500 ÷ 6250) × 100p = 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 × TTON = 0.40 × 50 µsTON = 20 µsTOFF = T − TONTOFF = 50 µs − 20 µsTOFF = 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) − 1TOP = 125,000,000 Hz ÷ (1 × 1000 Hz) − 1TOP = 124,999

The first result exceeds 65,535. Increase the divider to 2 and recalculate.

TOP = 125,000,000 Hz ÷ (2 × 1000 Hz) − 1TOP = 62,499fPWM = 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

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 algorithm

Before 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.

  1. Start the program and configure Button A’s GP0 pin as a digital input with a pull-up.
  2. Initialize last_pressed so the first reading is reported.
  3. Repeat: read the pin and convert the active-low logic level into a pressed/released state.
  4. Check whether the state differs from the previous reading.
  5. If it changed, print the new state and store it as the previous state.
  6. Wait briefly, then read the pin again.
Button A state-change flowchartStart, 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.STARTConfigure GP0 input + pull-uplast_pressed = NoneRead Button Apressed = NOT button.valueState changed?pressed ≠ last_pressedYESNO · skip printPrint pressed / releasedUpdate last_pressedcontinueWait 20 msREPEAT 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 toolbar

Thonny 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− □ ×
FileEditViewRunToolsHelp
② 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 areaFunction in the lesson
New, Open, SaveCreate, 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 · F5Execute the editor’s current program with the selected interpreter. Look at the Shell for printed output.
Debug current scriptStart 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 backendInterrupt a program that is running continuously or reset the interpreter connection.
EditorArea where Python statements are written and edited. Syntax highlighting can help distinguish names, strings, and keywords.
Shell / consoleShows print() output and tracebacks; its >>> prompt can accept interactive Python commands when the board is connected.
Files pane and interpreter/backend statusHelp 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.

03 / CONNECT THE BOARD

1.3.3 Connect the EDU PICO and check the firmware

Thonny runs on the computer, but the CircuitPython program runs on the microcontroller. The interpreter setting determines where Thonny sends the code.

  1. Connect the EDU PICO using a USB cable that supports data.
  2. 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.
  3. Check whether the board exposes its CIRCUITPY drive. If CircuitPython is already installed and the drive is available, continue without reinstalling firmware.
  4. 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.
  5. 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.py

For 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")
  1. Create a new file in the editor.
  2. Choose Run current script (commonly F5). Read both output lines in the Shell.
  3. Save a copy on the computer so the original work is backed up.
  4. For automatic execution by CircuitPython, save/copy the program to the root of the CIRCUITPY drive with the exact name code.py.
  5. 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 experiments

REPL 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 console

These 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 errors

Error typeWhat happensExample and debugging clue
Syntax errorPython 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 errorThe 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 errorThe 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.
  1. Read the complete Shell message, especially the exception type and reported line.
  2. Compare that line with the program and the expected algorithm.
  3. Change one thing at a time, save, and run again.
  4. Check the observed output or hardware state against the prediction.
  5. 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 message

This 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

  1. Change the message and predict the output before running the modified program.
  2. Intentionally remove a closing bracket. Record the syntax error and fix it.
  3. Change pressed = not button.value to pressed = button.value. Observe the reversed behavior and explain the logic error.
  4. Draw the algorithm as a flowchart and compare it with the running code.

08 / ADDITIONAL WORKED EXAMPLES

1.3.8 More examples and guided tutorials

Use 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

  1. 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 V

The 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)
  1. Confirm that the matching adafruit_debouncer library is installed in CIRCUITPY/lib; otherwise the import will raise an error.
  2. Save this program as code.py, run it, and press Button A three times.
  3. 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 fragmentYour 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
  1. print("Board ready" has a missing closing parenthesis: a syntax error. Correct it to print("Board ready").
  2. Use == to compare values; a single = is assignment and is invalid in this if condition. Write if temperature_c == 30:.
  3. 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.
  4. 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

  1. Modify Tutorial B to print “Check sensor” when the reading equals the set point.
  2. Modify Tutorial C to report both the press count and the active-low logic level when Button A is pressed.
  3. 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.

Six-question MCQ check — 1.3 Software development for the microcontroller

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. What is Thonny used for in this course?

Course outcome: CLO1 · Bloom level: Understand

2. Which action runs the current script in Thonny?

Course outcome: CLO1 · Bloom level: Apply

3. For a CircuitPython board, what filename normally runs automatically at startup?

Course outcome: CLO1 · Bloom level: Apply

4. A line ends with `if pressed` but has no colon. What kind of problem is this?

Course outcome: CLO1 · Bloom level: Analyze

5. A program starts but repeats the same output forever. Which issue should be checked first?

Course outcome: CLO1 · Bloom level: Analyze

6. In a flowchart, which shape normally represents a decision such as “button pressed?”

Course outcome: CLO1 · Bloom level: Apply

Not checked yet

CHAPTER 02

System Outputs

YOUR LEARNING GOALS

Chapter 2 learning outcomes

By the end of this chapter, students should be able to:

  1. Distinguish output devices from the information or physical actions they produce, and select a suitable indicator, display, or actuator for a stated application.
  2. 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.
  3. 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.
  4. Initialize the EDU PICO OLED using the adafruit_ssd1306 library and display text, numerical values, and system status at specified screen positions.
  5. Calculate PWM period, frequency, and duty cycle, and configure suitable waveforms for a specified output task.
  6. 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.

CHAPTER 2 / SUBTOPIC 2.1

2.1 Introduction to system outputs

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 outputA program decision creates a controller output signal, which reaches a suitable interface and output device to produce an observable result.PROGRAMdecisionCONTROLLERoutput signalINTERFACEif requiredDEVICEobservable 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 devices

Start by reading each highlighted definition. Then open the card to see the device’s function and an example.

IndicatorDefinition: 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.

DisplayDefinition: 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.

ActuatorDefinition: 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 outputs

Imagine 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 conditionTank is fullProgram decision: warn the user

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 understanding

Choose the best category for each example. You’ll get immediate feedback.

1. A lamp lights when a device is powered on.

2. A small screen shows the measured temperature as text and numbers.

3. A motor moves a vent to change airflow.

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.

Six-question MCQ check — 2.1 Introduction to system outputs

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. What makes a device an output device in an embedded system?

Course outcome: CLO1 · Bloom level: Understand

2. A controller must alert a user with a short audible tone. Which output is most suitable?

Course outcome: CLO1 · Bloom level: Apply

3. A temperature sensor sends a value to the RP2040. How should the sensor be classified in this signal path?

Course outcome: CLO1 · Bloom level: Analyze

4. Which device is an actuator that can create mechanical movement?

Course outcome: CLO1 · Bloom level: Apply

5. A status lamp is controlled by a GPIO pin. Which path is correct?

Course outcome: CLO1 · Bloom level: Analyze

6. A product needs to show a changing numeric reading and a simple status icon. Which output choice best meets both needs?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.2

2.2 Program template

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 parts

Program template: a reusable arrangement of code sections that gives a program a clear starting structure.

1 · ImportMake the required modules available.
2 · InitializePrepare the devices and pins before use.
3 · Main loopRepeat 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 needs

Import 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 time
  • board 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 them

Initialization: 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.OUTPUT

The 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 loop

Main 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 template

Select a code section to highlight it and see when it runs.

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 indentation

Comment: 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 understanding

Choose whether each instruction normally runs once during startup or repeatedly inside the main loop.

1. led.direction = digitalio.Direction.OUTPUT

2. led.value = not led.value when placed inside while True:

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.

Six-question MCQ check — 2.2 Program template

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. Why are modules imported near the beginning of a program?

Course outcome: CLO1 · Bloom level: Understand

2. Where should an output object normally be initialized?

Course outcome: CLO1 · Bloom level: Apply

3. What is the purpose of `while True:` in a typical interactive embedded program?

Course outcome: CLO1 · Bloom level: Analyze

4. A line intended to run inside `while True:` is aligned with the `while` statement. What is the likely effect?

Course outcome: CLO1 · Bloom level: Analyze

5. Which statement pauses a loop for 0.5 seconds when `time` has been imported?

Course outcome: CLO1 · Bloom level: Apply

6. Why should a program release a hardware resource when it is no longer needed?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.3

2.3 Built-in and library functions

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 programs

Built-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.

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 objects

Not 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 own

User-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 running

Source: 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 call

Choose the best category for each example. Immediate feedback explains the distinguishing clue.

1. len(samples)

2. time.sleep(1)

3. microphone.record(samples, count)

4. adc_to_voltage(32768, 3.3)

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.

Six-question MCQ check — 2.3 Built-in and library functions

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 is a Python built-in function?

Course outcome: CLO1 · Bloom level: Understand

2. What does `math.sqrt(25)` illustrate when `math` is imported?

Course outcome: CLO1 · Bloom level: Understand

3. In `display.show()`, what does the dot notation indicate?

Course outcome: CLO1 · Bloom level: Analyze

4. What does `def alarm():` do?

Course outcome: CLO1 · Bloom level: Apply

5. A program calls `pixels.show()` after setting pixel colours. What is its role?

Course outcome: CLO1 · Bloom level: Analyze

6. Why use a library function instead of writing a low-level device protocol from scratch?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.4

2.4 Output operations

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 output

Digital 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 value

Output 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 LOW

The 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 outputs

Active-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

GPIO output: LOW · approximately 0 V

Active-high · GPIO sources current

Active-high LED output schematicAn 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.RP2040GPIO output330 ΩLEDIGND

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 schematic3.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 Vsupply330 ΩLEDIRP2040GPIO 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 operation

Place 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 GP22

The 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.

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 understanding

Choose the best answer. Each response explains what the code or signal means.

1. What does relay.switch_to_output(value=False) do?

2. In an active-low circuit, when is the device active?

3. In the supplied GP22 relay example, what starting value represents “disabled”?

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.

Six-question MCQ check — 2.4 Output operations

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. What must be selected before setting a digital GPIO output value?

Course outcome: CLO1 · Bloom level: Understand

2. For an active-high LED circuit, what does setting its GPIO output to HIGH normally do?

Course outcome: CLO1 · Bloom level: Apply

3. What is the key difference between active-high and active-low control?

Course outcome: CLO1 · Bloom level: Analyze

4. Why is a current-limiting resistor placed in series with an ordinary LED?

Course outcome: CLO1 · Bloom level: Apply

5. A GPIO output object is configured with `value = False`. What is the most direct interpretation?

Course outcome: CLO1 · Bloom level: Analyze

6. Which is the safest choice for driving a motor from an RP2040 system?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.5

2.5 Light-emitting diode — LED

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 operation

Light-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 AR = (Vsupply − VF) ÷ IR = (3.3 V − 2.0 V) ÷ 0.005 AR = 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) ÷ RI = (3.3 V − 2.0 V) ÷ 330 ΩI ≈ 0.00394 AI ≈ 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 LEDs

RGB 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.

WS2812 schematic showing RP2040 GPIO 14 connected to DIN of Pixel 0, DOUT-to-DIN daisy chain through Pixel 4, and each pixel supplied from 3.3 V and common 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.
WS2812B PCB package drawing showing pin 1 VDD, pin 2 DOUT, pin 3 VSS, and pin 4 DIN
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
PinNamePurpose and connection
1VDDPositive 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.
2DOUTSerial data output. It forwards the remaining pixel data to the next WS2812B’s DIN. The final pixel’s DOUT is normally left unconnected.
3VSSGround (0 V) reference. Connect it to the common ground shared by the controller and LED supply.
4DINSerial 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 CircuitPython

NeoPixel 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 data

Read the constructor arguments as the hardware and behaviour settings for the pixel chain:

Meaning of the NeoPixel() arguments
ArgumentMeaning 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 selection

Adjust 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 stripFive WS2812 pixels are labelled with their CircuitPython indexes, 0 through 4. They display the selected colour and brightness.Pixel 0Pixel 1Pixel 2Pixel 3Pixel 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 strip

The 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 0Pixel 1Pixel 2Pixel 3Pixel 4

Software buffer: OFF for all pixels

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 understanding

  1. Set all five pixels to a colour of your choice using fill().
  2. Clear the strip, then set only the centre pixel. Which zero-based index is the centre pixel?
  3. 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?

2. Which call assigns the same colour to all five pixels?

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.

Six-question MCQ check — 2.5 Light-emitting diode — LED

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. What does a series resistor do in an ordinary LED circuit?

Course outcome: CLO1 · Bloom level: Understand

2. For a common-cathode seven-colour RGB LED package with separate channels, how is a channel commonly turned on?

Course outcome: CLO1 · Bloom level: Apply

3. How is an onboard WS2812/NeoPixel typically controlled?

Course outcome: CLO1 · Bloom level: Understand

4. What does `pixels[0] = (255, 0, 0)` request from a NeoPixel object?

Course outcome: CLO1 · Bloom level: Apply

5. With `auto_write=False`, why call `pixels.show()` after changing colours?

Course outcome: CLO1 · Bloom level: Analyze

6. Why should an ordinary LED not be connected directly between a GPIO and ground without current limiting?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.6

2.6 Seven-segment display

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 numeral

Seven-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.

Interactive labelled seven-segment numeralSelect a digit from zero to nine. Its active LED segments illuminate and are named a through g; the decimal point can be toggled.abcdefgdp

Digit 8 uses segments a, b, c, d, e, f, g.

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)
DigitSegments ONDigitSegments ON
0a, b, c, d, e, f5a, c, d, f, g
1b, c6a, c, d, e, f, g
2a, b, d, e, g7a, b, c
3a, b, c, d, g8a, b, c, d, e, f, g
4b, c, f, g9a, 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 displays

Common 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.

Comparison of common-cathode and common-anode seven-segment LED displays, showing segment labels, package pin assignments, and internal LED connections
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 multiplexing

Multiplexing: 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 module

TM1650 four-digit seven-segment circuit schematic showing EDU PICO GPIO5 connected to SCL, GPIO4 connected to SDA, 3.3 V and ground power, and the TM1650 DIG and segment pins connected to the four-digit LED module
Figure 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 signalEDU PICO connectionPurpose
SDAGP4 · I²C dataTransfers commands and display data
SCLGP5 · I²C clockTimes I²C communication
VCC / GND3V3 / GND via I²C Grove connectionPower 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 CircuitPython

Install 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
CodeEffect
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 wraparound

Enter 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.

Interactive four-digit seven-segment counterA four-digit simulated TM1650 display shows a zero-padded count from 0000 to 9999. Step past 9999 to wrap to 0000.

Display: 0007

text = "{:04d}".format(7)
display.show(text)
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 understanding

  1. Write the segment names that must be ON to display digit 4.
  2. Explain why a common-anode segment typically turns ON with a LOW output, while a common-cathode segment turns ON with a HIGH output.
  3. What is the purpose of multiplexing four digits?
  4. What does "{:04d}".format(25) produce?
  5. Starting at 9998, list the next three displayed values when the counter uses (count + 1) % 10000.

1. Which segments make the numeral 1?

2. What does "{:04d}".format(7) return?

3. How does the M18 RP2040 send display data to the TM1650?

4. What follows 9999 when (count + 1) % 10000 is used?

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

2. What changes between common-anode and common-cathode displays?

Course outcome: CLO1 · Bloom level: Analyze

3. What is the purpose of the decimal-point segment?

Course outcome: CLO1 · Bloom level: Understand

4. Why does a multi-digit display often enable digits one at a time rapidly?

Course outcome: CLO1 · Bloom level: Apply

5. In an EDU PICO display using a TM1650 controller, what does the controller simplify?

Course outcome: CLO1 · Bloom level: Analyze

6. A digit pattern lights all outer bars but not the middle bar. Which numeral is represented?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.7

2.7 OLED display interfacing

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 lines

I²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.

SSD1306 128 by 64 OLED wiring diagram with 3.3 volt, ground, SCL and SDA connections between RP2040 and display; the drawing labels GP4 as SCL and GP5 as SDA
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 display

This 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
StepWhat it does
Import librariesboard 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 busbusio.I2C(board.GP5, board.GP4) uses GP5 for SCL (clock) and GP4 for SDA (data).
Create the display objectSSD1306_I2C(128, 64, i2c) sets the OLED size and connects it to the bus.
Draw and send textfill(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 coordinates

Coordinate: 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.

Text starts at x = 4 px, y = 14 px.

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 data

Update 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.

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 reading

Suppose 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.

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 checks

OLED troubleshooting guide
SymptomCheck
ImportError for the SSD1306 driverInstall a CircuitPython-compatible adafruit_ssd1306 library and its required dependencies in CIRCUITPY/lib; avoid mixing versions.
I²C scan does not find 0x3CCheck power, ground, SDA/SCL wiring, selected pins, and the display's actual address.
Display stays blankRead the Thonny Shell traceback; verify OLED dimensions, I²C bus, driver, and that show() is called after drawing.
Text is clippedReduce message length or x/y position; keep the text within the 128 × 64 pixel area.
Display setup fails after rerunCheck 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 interfacing

Choose one answer for each question. Feedback appears after you select an option.

1. What does SSD1306_I2C(128, 64, i2c) do?

2. In oled.text(text, x, y, 1), what does y specify?

3. In oled.text(text, x, y, 1), what does the fourth argument do?

4. What happens if a two-placeholder string calls .format(voltage)?

5. What makes newly drawn text visible on the OLED?

6. Which expression estimates voltage from a 16-bit ADC reading?

2.7.9 Practice tasks

  1. Initialize the OLED at 0x3C and display your name on the first line.
  2. Display a counter that increases once per second; add Status: READY.
  3. Read GP28 and show the raw ADC value and approximate voltage, updating five times per second.
  4. 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

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 cycle

Period (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 ÷ fT = 1 ÷ 200 HzT = 5000 µsd = p ÷ 100d = 40 ÷ 100d = 0.4TON = d × TTON = 0.4 × 5000 µsTON = 2000 µsTOFF = T − TONTOFF = 5000 µs − 2000 µsTOFF = 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 ÷ fT = 1 ÷ 1,000 HzT = 1000 µsd = p ÷ 100d = 25 ÷ 100d = 0.25TON = d × TTON = 0.25 × 1000 µsTON = 250 µsTOFF = T − TONTOFF = 1000 µs − 250 µsTOFF = 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 output

Change 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.

Period: 5 ms · HIGH: 2 ms · LOW: 3 ms

LED brightness
40% PWM drive command
Frequency effect · buzzer pitchSelected tone: 200 HzClick to hear a short browser-generated square-wave tone. Course hardware example: buzzer on GP21.
Interactive PWM waveformA square wave changes its pulse width with duty cycle and its number of cycles in the displayed time window with frequency.HIGHLOWTime window: 20 ms0

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 CircuitPython

pwmio.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
ItemMeaning
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 setting

To convert a requested duty percentage into CircuitPython's 0–65535 range, use:

Example duty-cycle settings (rounded down to integer)
DutyPWM valueInterpretation
0%0Always LOW; output is off.
25%16383HIGH for one quarter of each cycle.
50%32767HIGH and LOW durations are approximately equal.
75%49151HIGH for three quarters of each cycle.
100%65535Always 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 course

How frequency and duty are used by EDU PICO examples
ApplicationCourse exampleWhat frequency controlsWhat duty or command controls
Buzzer · GP2103_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/GP1106_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 · GP607_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 tutorial

  1. A 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.
  2. Convert 60% duty to a CircuitPython setting.
    Check: int(0.60 × 65535) = 39321.
  3. 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.

Six-question MCQ check — 2.8 Pulse-width modulation — PWM

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. What does PWM duty cycle describe?

Course outcome: CLO1 · Bloom level: Understand

2. A 1 kHz PWM signal has a 25% duty cycle. What is its period?

Course outcome: CLO1 · Bloom level: Apply

3. For ideal 3.3 V PWM at 50% duty, what is the approximate average voltage after suitable low-pass averaging?

Course outcome: CLO1 · Bloom level: Analyze

4. What does the `TOP` value set in a PWM counter?

Course outcome: CLO1 · Bloom level: Understand

5. If a 16-bit `duty_cycle` is set to 32768, what is the approximate duty cycle?

Course outcome: CLO1 · Bloom level: Apply

6. Why can a PWM-driven motor’s speed change when duty cycle changes while frequency remains fixed?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.9

2.9 Buzzer

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 sound

Buzzer: 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 connection

Before 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.

EDU PICO buzzer driver circuit: GP21 drives the gate of a BSS138 MOSFET through a 1 kilo-ohm resistor; the MOSFET switches a 3.3 volt buzzer to ground, with an SS14 diode across it
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.
Course booklet illustration of the EDU PICO piezo buzzer and the switch positions for buzzer and audio output
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 duration

Frequency, 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
QuantityWhat it changesExample
Frequency (Hz)Pitch of the tone440 Hz sounds lower than 880 Hz
Duty cycle (%)Fraction of each cycle that is HIGH50%: equal HIGH and LOW portions
Duration (s)Length of a note or beep1 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 ÷ fT = 1 ÷ 440 HzT ≈ 0.002273 sT ≈ 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 HzT = 1 msTON = d × TTON = 0.5 × 1 msTON = 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 seconds

The 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.PWMOut

pwmio.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 resource

The 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
ParameterMeaning 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 frequency

Select 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.

440 Hz · period 2.27 ms · about A4

PWM waveform for the selected buzzer frequencyA 50 percent duty cycle square wave in a fixed 10 millisecond window. Frequency changes the number of cycles in the window.HIGHLOWtime → · 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 understanding

  1. Calculate the period of a 1 kHz buzzer signal.
  2. A 440 Hz tone is played for 0.5 s. Approximately how many signal cycles are generated?
  3. Explain why the duty cycle is not the same quantity as tone duration.
  4. Write two beeps at different pitches with a short silent gap between them.

1. Which setting primarily changes the pitch of a passive buzzer?

2. What is the period of a 500 Hz signal?

3. In the PWM example, what does setting duty_cycle = 0 do?

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.

Six-question MCQ check — 2.9 Buzzer

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 does a passive buzzer produce different pitches?

Course outcome: CLO1 · Bloom level: Understand

2. A 440 Hz tone has a period closest to:

Course outcome: CLO1 · Bloom level: Apply

3. Why is a transistor/MOSFET stage used in the EDU PICO buzzer circuit?

Course outcome: CLO1 · Bloom level: Analyze

4. In `simpleio.tone(pin, frequency, duration=...)`, what does `frequency` specify?

Course outcome: CLO1 · Bloom level: Apply

5. What happens to perceived pitch when the tone frequency increases?

Course outcome: CLO1 · Bloom level: Analyze

6. Why should a tone preview be stopped or its hardware resource released when finished?

Course outcome: CLO1 · Bloom level: Evaluate

Not checked yet

CHAPTER 2 / SUBTOPIC 2.10

2.10 DC motor

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 driver

DC 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?
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

EDU PICO motor-driver schematic. GP10 and GP11 connect to the MX1515H/MX1515H driver's Motor 1 inputs; GP12 and GP13 connect to Motor 2. The chip is powered from 3.3 V logic and a separate 5 V motor supply, with driver grounds connected to ground.
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 command

Throttle: 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.

Clockwise (CW) · 40% throttle command

Interactive MOTOR2 H-bridge control and GPIO PWM valuesRP2040 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 CONTROLGPIO13PWM 40%GPIO12PWM 0%MX1515HH-bridgeM2 channelM2CLOCKWISE (CW)ThrottlemagnitudeGPIO 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 CircuitPython

The 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
CodeMeaning
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 example

The 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 ÷ fT = 1 ÷ 10,000 HzT = 100 µsd = p ÷ 100d = 40 ÷ 100d = 0.4TON = d × TTON = 0.4 × 100 µsTON = 40 µsTOFF = T − TONTOFF = 100 µs − 40 µsTOFF = 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 ÷ fT = 1 ÷ 10,000 HzT = 100 µsd = p ÷ 100d = 75 ÷ 100d = 0.75TON = d × TTON = 0.75 × 100 µsTON = 75 µsTOFF = T − TONTOFF = 100 µs − 75 µsTOFF = 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 ÷ fT = 1 ÷ 20,000 HzT = 50 µsd = p ÷ 100d = 40 ÷ 100d = 0.4TON = d × TTON = 0.4 × 50 µsTON = 20 µsTOFF = T − TONTOFF = 50 µs − 20 µsTOFF = 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 troubleshooting

  1. With 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.
  2. Run the supplied example and identify the order: clockwise (CW) 0.4, coast, counterclockwise (CCW) 0.4, coast.
  3. 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.
  4. If the motor does not turn, check the driver supply, terminal connection, selected pins (GP10/GP11 for M1), library installation, and Thonny Shell errors.
  5. 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.

Six-question MCQ check — 2.10 DC 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. Which H-bridge driver IC is used in the EDU PICO motor-drive circuit?

Course outcome: CLO1 · Bloom level: Understand

2. In the course motor library, what does a positive throttle command indicate?

Course outcome: CLO1 · Bloom level: Apply

3. In the course example, what is the difference between `throttle = None` and `throttle = 0.0`?

Course outcome: CLO1 · Bloom level: Analyze

4. Why is PWM commonly used for motor speed control?

Course outcome: CLO1 · Bloom level: Understand

5. Why must a DC motor not be connected directly to an RP2040 GPIO?

Course outcome: CLO1 · Bloom level: Evaluate

6. The motor turns the opposite way from the requested command. Which software property should be checked first?

Course outcome: CLO1 · Bloom level: Analyze

Not checked yet

CHAPTER 2 / SUBTOPIC 2.11

2.11 Stepper motor

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.

28BYJ-48 five-wire unipolar stepper motor connected to a ULN2003 driver; inset shows shared-common unipolar winding and driver connections.

Unipolar: course 28BYJ-48 with ULN2003 driver

Cutaway of a two-phase hybrid bipolar stepper motor showing its toothed permanent-magnet rotor, stator coils and stator core.

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
FeatureUnipolar — course 28BYJ-48Bipolar
Typical winding connectionsFive-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 changedCurrent 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 driverFour 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.
AdvantagesSimpler 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.
TradeoffsUsually 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 practicalYes. 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.
Interactive circular stepper winding diagram Four stator winding poles surround a permanent-magnet rotor. Select unipolar or bipolar operation and step through the sequence to highlight energized poles and rotate the rotor. B A C D NS Stator windings create a moving magnetic field
Step 1 of 4

Current path+Vm → common lead → phase A winding → ULN2003 switch → GND

Unipolar, step 1 of 4: phase A is energized. The field moves and the rotor follows.

Unipolar: a shared common feeds winding sections; switches select sections without reversing current through each section.

AdvantageSimple four-switch drive; matches the course 28BYJ-48 and ULN2003.

Trade-offThe shared common needs correct wiring and only part of a centre-tapped phase is used at a time.

Highlighted winding = energized stator pole

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.
Source for the motor-type concepts and typical 28BYJ-48 construction: RS DesignSpark, “Microcontroller Interfaces: Stepper Motors”. The article's typical gearbox/step-count figures are illustrative and should not replace the datasheet for the exact motor fitted.

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 typeConceptual sequenceHow 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.

ULN2003 stepper driver schematic. EDU PICO GPIO26, GPIO27, GPIO8 and GPIO7 connect to driver inputs 1IN through 4IN. Driver outputs 1OUT through 4OUT connect to stepper coil A through D. The driver common is connected to 5 volts, and four LED and 500-ohm branches indicate the output channels.
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
PartIts role
RP2040 GPIOSends a small 3.3 V control signal to one ULN2003 input; it does not carry the motor-coil current.
ULN2003Acts 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 supplyProvides 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.
  1. Current capacity: the driver switches the coil current, keeping that load off the microcontroller GPIO.
  2. 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.
  3. 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 rate

Calculate 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 × Δtfstep = 1 ÷ Δts = 60 × fstep ÷ N
28BYJ-48 nominal output-shaft calculations — assuming a 64:1 gearbox
Drive modeAdafruit styleIncrements per 360°Output angle per incrementCalls for 90° / 180° / 360°
Wave drive / two-phase full-stepstepper.SINGLE / stepper.DOUBLE32 × 64 = 2,048360° ÷ 2,048 = 0.17578125°512 / 1,024 / 2,048
Half-step — course codestepper.INTERLEAVE64 × 64 = 4,096360° ÷ 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 × Δtt = 128 × 0.005 st = 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 ÷ Δtfstep = 1 ÷ 0.005 sfstep = 200 increments/st = N × Δtt = 4096 × 0.005 st = 20.48 ss = 60 × fstep ÷ Ns = 60 × 200 ÷ 4096s ≈ 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 × Δtt = 768 × 0.005 st = 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.

Half-step sequence · state 1 of 8

Animated four-phase stepper motor sequenceFour stator poles surround a centered rotor. Energized phases highlight as the sequence advances; the rotor indicator aligns with the resultant field.ABCDROTORHighlighted poles are energized in the selected state
Phase output states · ON = 1, OFF = 0
A :B :C :D :
1ON0OFF0OFF0OFF
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
CheckWhy it matters
Driver and motor compatibilityThe driver must match motor type, coil current, voltage, and phase arrangement.
Supply and groundUse a motor supply rated for the load and a shared ground/reference as required by the driver.
Coil orderAn incorrect order can cause vibration, weak torque, or no rotation; verify wiring from the driver/motor documentation.
Step rate and loadStarting too quickly or demanding excessive torque can make the motor miss steps.
Position referenceOpen-loop step counting estimates movement from a known home position; use a limit switch or other reference when absolute position matters.
Release behaviorReleasing 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

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

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

4. Why does the course stepper example require an external driver?

Course outcome: CLO1 · Bloom level: Analyze

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

6. Why can an open-loop step count fail to give the mechanism’s true absolute position?

Course outcome: CLO1 · Bloom level: Analyze

Not checked yet

CHAPTER 2 / SUBTOPIC 2.12

2.12 Servo motor

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.

Block diagram of a positional servo: PWM command enters a converter, the error signal is amplified to drive the motor and gears, while a potentiometer measures output shaft position and feeds it back.
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.
Disassembled hobby servo showing the control circuit, DC motor, position potentiometer, drive gears, servo case, and output spline.
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 widthApproximate commanded angleDuty ratio in a 20 ms frameWhat the servo does
1.0 ms0°1 ÷ 20 × 100 = 5%Moves toward one end of its calibrated travel
1.5 ms90°1.5 ÷ 20 × 100 = 7.5%Moves toward the midpoint
2.0 ms180°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 ÷ fT = 1 ÷ 50 HzT = 0.020 sT = 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 ÷ Td = 1.5 ms ÷ 20 msd = 0.075u ≈ 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).

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 elementMeaning
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.

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 simulationAn 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 modelhorn angle follows the commandOne PWM frame · 20 ms0 ms20 msHIGH 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

  1. With power off, confirm the servo plug's signal, positive, and ground orientation at the EDU PICO servo port.
  2. Run the finite angle example with the servo horn unloaded. Confirm that each new angle command moves the horn toward a new position.
  3. Turn the onboard potentiometer slowly and compare its direction with the requested angle shown in the Thonny Shell or an optional display.
  4. 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.
  5. 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.
References: Course example 20262027/lecture_examples/07_servo.py and EDU PICO notes (GP6 servo signal; onboard potentiometer GP28). See the Adafruit Motor Servo API for angle, pulse-range, and release behavior, and the official servo sweep example.

Six-question MCQ check — 2.12 Servo motor

Assessment alignment: CLO1 conceptual understanding and application, with analysis of control and hardware behavior. Bloom levels are shown per question. CLO2 practical competency will be assessed through the integrated laboratory tasks planned after Chapter 5; this quiz does not substitute for that practical assessment.

1. What distinguishes a positional hobby servo from a simple DC motor?

Course outcome: CLO1 · Bloom level: Understand

2. What is the frame period for a 50 Hz servo command?

Course outcome: CLO1 · Bloom level: Apply

3. A 1.5 ms HIGH pulse repeats every 20 ms. What is its duty ratio?

Course outcome: CLO1 · Bloom level: Apply

4. The servo is configured for 1,000 μs at 0° and 2,000 μs at 180°. Which pulse is the midpoint command?

Course outcome: CLO1 · Bloom level: Apply

5. Which statement about wiring the EDU PICO servo is safest and most accurate?

Course outcome: CLO1 · Bloom level: Evaluate

6. A servo buzzes continuously at the commanded 180° endpoint. What is the best first response?

Course outcome: CLO1 · Bloom level: Analyze

Not checked yet

CHAPTER 03

System Inputs

YOUR LEARNING GOALS

Chapter 3 learning outcomes

By the end of this chapter, students should be able to:

  1. Classify input signals as analogue, digital GPIO states, or digitally communicated sensor data, and select an appropriate acquisition method.
  2. Configure and read GPIO inputs in CircuitPython, explain pull-up/pull-down operation, and implement a debounced button-controlled action.
  3. Calculate ADC resolution and convert between voltage and digital readings while distinguishing the RP2040 hardware resolution from the analogio output scale.
  4. 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.
  5. Explain matrix-keypad scanning and determine a pressed key from row-and-column states, identifying the external hardware required.
  6. 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.

CHAPTER 3 / SUBTOPIC 3.1

3.1 Introduction to system inputs

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 systemA person or physical condition affects an input device. The device produces a signal which the RP2040 reads and interprets before controlling an output.EventInput deviceSignalRP2040Responsepress / temperaturebutton / sensorvoltage / dataread + interpretdisplay / actuatorThe 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.

EDU PICO course board and input components used in the course
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 categoryWhat arrives?EDU PICO exampleHow the RP2040 receives itCovered in
Digital GPIO stateOne 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 levelA 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 dataBits 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 OLEDRP2040 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.RP2040I²C controllerGP5 · SCLGP4 · SDASCL · clockSDA · dataSCL · shared clockSDA · shared dataAHT20Target · 0x38OLEDTarget · 0x3CBoth 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 bitsStart, 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.SCLclockSDAdataR/W bitIDLESTARTADDRESS + WMEASUREMENT COMMANDWAITADDRESS + RREAD DATASTOPW = 0R = 10xAC · 0x33 · 0x00 + ACK after each byteD7 … D0 · ACK · … · final NACK≥80 msSTARTSTOPSCLSDA
SCL · CLOCKHIGH
SDA · DATAHIGH
BUS IDLESCL = HIGH · SDA = HIGHBus is idle; pull-ups hold both lines HIGH.

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

  1. The RP2040 addresses the AHT20 at 0x38 and writes the measurement trigger command: 0xAC, 0x33, 0x00.
  2. The controller waits at least 80 ms for the sensor to complete its measurement, then checks that the sensor is ready.
  3. 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 SDA

busio.I2C(...)

Creates an I²C controller object. CircuitPython’s argument order is clock pin first, then data pin.

board.GP5

Connects SCL, the clock line, to EDU PICO GP5.

board.GP4

Connects 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

Quick check: system inputs

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, Analyse. These questions assess concepts and classification; practical CLO2 performance is assessed later through integrated lab work.

1. What is a system input?

CLO1 · Bloom: Remember

2. Which example is a user command?

CLO1 · Bloom: Understand

3. The program reads an onboard button connected to GP0. Which category best describes this input?

CLO1 · Bloom: Apply

4. Why is the EDU PICO potentiometer read through an ADC input?

CLO1 · Bloom: Understand

5. What distinguishes the AHT20 input from a simple button GPIO?

CLO1 · Bloom: Analyse

6. A student wants to read a knob position as a changing level. Which EDU PICO input is the best match?

CLO1 · Bloom: Apply

Score: —

Sources and further reading

CHAPTER 3 / SUBTOPIC 3.2

3.2 Input operations

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.

  1. Select: identify the signal pin and its wiring.
  2. Configure: set input direction and an appropriate pull.
  3. Read: obtain the electrical logic level.
  4. Interpret: decide what that level means for this circuit.
  5. 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.

RP2040 input voltage regions for 3.3 volt I/O supplyLOWNot guaranteedHIGH0 V0.8 V2.0 V3.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.

ArrangementSwitch openSwitch closedInterpretation
Pull-up; switch to GNDHIGH / TrueLOW / FalseActive-low; EDU PICO button A/B arrangement
Pull-down; switch to 3.3 VLOW / FalseHIGH / TrueActive-high; external teaching circuit
No bias and no external driveFloatingDepends on switch railUnreliable 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.

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 ÷ RI = 3.3 V ÷ 10,000 ΩI = 0.00033 AI = 0.33 mAP = V2 ÷ RP = (3.3 V)2 ÷ 10,000 ΩP = 0.001089 WP = 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 ÷ RI = 3.3 V ÷ 4700 ΩI ≈ 0.702 mAP = V2 ÷ RP = (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 elementPurpose 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.

Configurable switch and pull resistor connected to an RP2040 digital inputRP2040GP0 · INPUT3.3 V (pull-up)Bias disconnectedGND3.3 V · HIGHConceptual circuit · ideal switch · no contact bounce

raw = button.valueif 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.

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 ÷ Tsfs = 1 ÷ 0.050 sfs = 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 ÷ Tsfs = 1 ÷ 0.010 sfs = 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.

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 time

time.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
  1. For a 4.7 kΩ external pull-up and a closed switch to GND at 3.3 V, calculate resistor current and power.
  2. If polling occurs at 0, 50 and 100 ms, predict whether a press from 20 to 40 ms is detected.
  3. 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

Six-question input analysis check

CLO1 · C4 target: analyse signal, wiring and program behaviour. Understand and Apply questions provide supporting checks. Hardware performance for CLO2 is assessed later.

1. With an active-low button and pull-up, the switch is released. Which pair is correct?

CLO1 · Bloom: Understand

2. A switch connects GPIO to GND. It has a pull-down, and raw stays False whether pressed or released. What explains this?

CLO1 · Bloom: Analyse

3. At IOVDD = 3.3 V, a GPIO measures 1.4 V. Which conclusion follows from the specified input limits?

CLO1 · Bloom: Analyse

4. An ideal 3.3 V circuit has a 10 kΩ pull-up and a closed switch to GND. What current flows through the pull resistor?

CLO1 · Bloom: Apply

5. Polling occurs at 0, 50 and 100 ms. An active-low press lasts from 20 to 40 ms. What should you predict?

CLO1 · Bloom: Analyse

6. One physical press gives several rapid HIGH→LOW transitions despite a correct pull-up. Which response addresses the likely cause?

CLO1 · Bloom: Analyse

Not checked yet

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

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.

ExampleSignal delivered to RP2040Suitable interfaceProgram result
EDU PICO potentiometerVariable wiper voltage on GP28ADC via analogioVoltage or knob percentage
External analogue sensor, after checking board compatibilityVoltage representing a measured quantityAvailable ADC input and any required conditioningA unit calculated from the sensor relationship
EDU PICO AHT20Encoded temperature/humidity data on I²CGP4 SDA / GP5 SCL with a sensor driverDegrees 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.

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

3.3.1 ADC

Quantization, 12-bit conversion, API scaling, calculations and annotated code.

3.3.3 Potentiometer

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.

Check your understanding · six MCQs

CLO1 · C4 analysis target, supported by Understand and Apply questions. Explain the measurement path when reviewing each answer.

1. Which is the analogue electrical input in the EDU PICO examples?

CLO1 · Bloom: Understand

2. A sensor measures continuously changing temperature but transmits I²C bytes. Which interface should the RP2040 use?

CLO1 · Bloom: Analyse

3. A 4 Hz periodic input is sampled once every 250 ms at the same phase. Which observation can occur?

CLO1 · Bloom: Analyse

4. A sensor is powered at 5 V. What must be established before wiring its output to this ADC?

CLO1 · Bloom: Analyse

5. Why does an ADC code need a voltage reference for interpretation?

CLO1 · Bloom: Understand

6. The displayed value has six decimal places but fluctuates. Which conclusion is justified?

CLO1 · Bloom: Analyse

Not checked yet

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

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 ÷ 2NLSB 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 = 2NL = 212L = 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

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.

QuantityRange / equationInterpretation
Raw hardware code k0–4095One of 4096 ADC code values
API reading r0–65535Software representation of the conversion
Estimated voltageV ≈ r × reference_voltage / 65535Normalised 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) × VrefVin ≈ (32,776 ÷ 65,535) × 3.3 VVin ≈ 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) × VrefVin ≈ (49,151 ÷ 65,535) × 3.3 VVin ≈ 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 elementPurpose
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.

Check your understanding · six MCQs

CLO1 · C4 analysis target, supported by Understand and Apply questions. Explain the measurement path when reviewing each answer.

1. How many codes are available from a 12-bit conversion?

CLO1 · Bloom: Understand

2. For the lesson’s ideal model, VREF = 3.3 V and VIN = 0.825 V. What is the raw 12-bit code?

CLO1 · Bloom: Apply

3. CircuitPython reports an AnalogIn.value up to 65535 on RP2040. What does this establish?

CLO1 · Bloom: Analyse

4. Which denominator defines the ideal 12-bit bin width?

CLO1 · Bloom: Apply

5. The actual reference is 3.2 V but the calculation uses 3.3 V. What will averaging many readings repair?

CLO1 · Bloom: Analyse

6. Why store reading = pot.value before calculating voltage and percentage?

CLO1 · Bloom: Analyse

Not checked yet

Sources: RP2040 datasheet §4.9; analogio API; RP2040 CircuitPython AnalogIn implementation.

CHAPTER 3 / SUBTOPIC 3.3.2

3.3.2 Temperature sensor

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) ÷ STC = (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) ÷ STC = (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

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 / objectPurpose
3.3 V and GNDOnboard supply and common reference.
SDA · GP4Shared I²C data.
SCL · GP5Shared I²C clock.
AHT20 address 0x38Selects 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.

Check your understanding · six MCQs

CLO1 · C4 analysis target, supported by Understand and Apply questions. Explain the measurement path when reviewing each answer.

1. How does the onboard AHT20 communicate its reading to the RP2040?

CLO1 · Bloom: Understand

2. For the hypothetical model V = 0.50 + 0.010T, what temperature corresponds to 0.75 V?

CLO1 · Bloom: Apply

3. A student calculates T = V/0.010 using the same model. Why is the result incorrect?

CLO1 · Bloom: Analyse

4. What is the argument order in busio.I2C(board.GP5, board.GP4)?

CLO1 · Bloom: Understand

5. A temperature sensor near a warm regulator reads higher than a remote reference thermometer. What should be investigated first?

CLO1 · Bloom: Analyse

6. A format string contains two numeric placeholders but .format() receives only temperature. What happens?

CLO1 · Bloom: Analyse

Not checked yet

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

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 VI = 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.

Linear potentiometer knob and divided resistance connected to GP28Virtual knob3.3 VGNDRhigh = 5 kΩRlow = 5 kΩWiper → GP281.650 V
Ideal raw ADC
API reading
Estimated percentage
VIRTUAL LEVEL DISPLAY

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) × VrefVin ≈ (16,384 ÷ 65,535) × 3.3 VVin ≈ 0.82501 Vp = 100 × r ÷ 65,535p = 100 × 16,384 ÷ 65,535p ≈ 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 VVin ≈ 2.47499 Vp = 100 × 49,151 ÷ 65,535p ≈ 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.

Check your understanding · six MCQs

CLO1 · C4 analysis target, supported by Understand and Apply questions. Explain the measurement path when reviewing each answer.

1. For Rhigh = 7.5 kΩ, Rlow = 2.5 kΩ and 3.3 V supply, what is the ideal wiper voltage?

CLO1 · Bloom: Apply

2. Reversing the potentiometer’s outer supply connections has which effect?

CLO1 · Bloom: Analyse

3. Which mapping expresses an AnalogIn.value as a nominal percentage?

CLO1 · Bloom: Understand

4. A disconnected wiper produces unstable readings. What is the first useful action?

CLO1 · Bloom: Analyse

5. Measured endpoints are 1000 and 64000; the reading is 32500. What is the calibrated percentage?

CLO1 · Bloom: Apply

6. Averaging makes the knob display steadier but slower. Which interpretation is appropriate?

CLO1 · Bloom: Analyse

Not checked yet

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

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 exampleElectrical interfaceProgram informationInterpretation
Buttons A / BGP0 / GP1 GPIOTrue or FalseApply active-low meaning, then detect state or event.
AHT20 humidityI²C: SDA GP4, SCL GP5Relative humidity (%)A numerical quantity transported digitally; see 3.1.5 I²C walkthrough.
APDS9960 light / colourShared I²C busRed, green, blue and clear channel countsClear is a broad light channel; raw counts are not automatically lux.
APDS9960 proximity / gestureShared I²C busProximity count or direction eventProximity is not a direct centimetre measurement. A gesture is an interpreted motion event.
Digital microphonePDM clock GP3 / data GP2Audio samples after PDM captureRMS counts indicate signal magnitude; calibrated sound pressure is needed for dB SPL.
External capacitive keypadUART example: GP20 TX / GP21 RXEncoded key byteDecode 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

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.

ObservationRaw GP0Pressed = not rawResult
Released1 / TrueFalseNo press event
New press0 / FalseTrueOne press event
Still held0 / FalseTrueStill active; no new press edge
Released again1 / TrueFalseRelease 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 msTs = 0.010 sfs = 1 ÷ Tsfs = 1 ÷ 0.010 sfs = 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.

Check your understanding · six MCQs

CLO1 (C4): build from Understand and Apply to Analyse. These questions support conceptual reasoning; formal CLO2 practical assessment follows Chapter 5.

1. A digital-input GPIO reading primarily represents…

CLO1 · Bloom: Understand

2. Which interface reads onboard AHT20 humidity?

CLO1 · Bloom: Understand

3. An active-low button changes from raw True to False. This is…

CLO1 · Bloom: Apply

4. An ideal 10 ms polling interval corresponds to…

CLO1 · Bloom: Apply

5. A 4 ms pulse sometimes disappears when sampling every 10 ms. The best explanation is…

CLO1 · Bloom: Analyse

6. An APDS9960 proximity count is displayed as centimetres without calibration. The problem is…

CLO1 · Bloom: Analyse

Not checked yet

CHAPTER 3 / SYSTEM INPUTS

3.4.1 Push button

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.

ConditionGPIO voltage (ideal)Raw valueMeaning
Released, pulled up3.3 VTrue / 1Not pressed
Pressed, connected to GND0 VFalse / 0Pressed

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.

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 GP0and current timeTrack candidateunchanged ≥ 20 msAccept changedstable stateIf 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()
ElementPurpose
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.

Check your understanding · six MCQs

CLO1 (C4): build from Understand and Apply to Analyse. These questions support conceptual reasoning; formal CLO2 practical assessment follows Chapter 5.

1. With the EDU PICO button released and pulled up, the raw value is…

CLO1 · Bloom: Understand

2. A toggle operation means…

CLO1 · Bloom: Understand

3. After one press is accepted, five unchanged held samples arrive. How many additional presses are counted?

CLO1 · Bloom: Apply

4. Two accepted presses start with pixel 0 OFF. Final state and count are…

CLO1 · Bloom: Apply

5. A raw input changes again before the 20 ms stability period finishes. The algorithm should…

CLO1 · Bloom: Analyse

6. A counter is correct, but an output becomes OFF immediately on release instead of remaining ON. Most likely…

CLO1 · Bloom: Analyse

Not checked yet

CHAPTER 3 / SYSTEM INPUTS

3.4.2 Keypad

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.

TypeWhat RP2040 receivesHow to read it
Raw mechanical 4 × 3 matrixFour row and three column connectionsScan 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 examplesUART key codesReceive and decode module bytes. The module handles touch sensing.
An I²C touch-controller variantI²C registers or eventsUse 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.

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 + columni = 2 × 3 + 1i = 7Tscan = Nrows × trowTscan = 4 × 0.002 sTscan = 0.008 sfscan = 1 ÷ Tscanfscan = 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 + columni = 2 × 3 + 1i = 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 × trowTscan = 4 × 2 msTscan = 8 msfscan = 1 ÷ Tscanfscan = 1 ÷ 0.008 sfscan = 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 changes

This 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 terminalEDU PICO connectionPurpose
TXGP21 / RXKeypad → RP2040 data
RXGP20 / TXRP2040 → keypad data, if required
VCC3.3 VSupply for the documented compatible module
GNDGNDShared 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.

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 ÷ fbusT = 1 ÷ 9600 sT ≈ 104.17 µsNbits = 1 + 8 + 1Nbits = 10tframe = Nbits ÷ fbustframe = 10 ÷ 9600 stframe ≈ 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 ÷ fbusT = 1 ÷ 9600 sT ≈ 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 + 1Nbits = 10tframe = Nbits ÷ fbustframe = 10 ÷ 9600 stframe ≈ 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 elementMeaning
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.

Check your understanding · six MCQs

CLO1 (C4): build from Understand and Apply to Analyse. These questions support conceptual reasoning; formal CLO2 practical assessment follows Chapter 5.

1. A 4-row, 3-column raw matrix has twelve keys and uses…

CLO1 · Bloom: Understand

2. A controller-based UART keypad differs from a raw matrix because…

CLO1 · Bloom: Understand

3. Using zero-based indexing in a three-column matrix, what is the key_number (index) for row R2 and column C1?

CLO1 · Bloom: Apply

4. At 9600 bit/s, an 8N1 frame takes approximately…

CLO1 · Bloom: Apply

5. Three corners of a diode-free matrix rectangle create an extra key report. The likely cause is…

CLO1 · Bloom: Analyse

6. The program receives 0xE8 from the documented UART module. Which interpretation is sound?

CLO1 · Bloom: Analyse

Not checked yet

CHAPTER 04

Software Components

YOUR LEARNING GOALS

Chapter 4 learning outcomes

By the end of this chapter, students should be able to:

  1. Explain the CircuitPython runtime and trace the structure of a microcontroller application.
  2. Use variables, data types, operators, decisions, loops, and collections in CircuitPython programs.
  3. Explain functions, objects, hardware constructors, timing, exceptions, and cleanup in the EDU PICO examples.
  4. 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.

CHAPTER 4 / SOFTWARE COMPONENTS

4.1 Introduction

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.

ComponentExample in this courseRole
Development environmentThonny on the computerEdit files, view output and diagnose errors; see 1.3.
Applicationcode.py on CIRCUITPYDefine the system’s required behaviour.
Library / moduleneopixel, analogioProvide reusable operations; some modules are built into firmware, while others are installed in lib.
Runtime firmwareCircuitPython build for the boardExecute the application and provide native hardware services.
HardwareRP2040, ADC, GPIO and EDU PICO devicesAcquire 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.

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.

ItemWhere / when it is usedEffect of restart
CircuitPython firmware and saved filesBoard flash storage; CIRCUITPY exposes the user filesystemNormally persist; a firmware replacement or storage erase is a separate operation.
boot.py (optional)Startup configuration before normal workflowsNot required for this example; it is not the repeating application loop.
code.pyMain application after normal startup or reloadRuns again from its initialisation.
Variables, sampled readings and object stateWorking RAMRecreated by the program; not automatically saved to a file.
lib/Installed support librariesUse versions compatible with the installed CircuitPython release.
Power / resetNormal bootCircuitPython startsOptional boot.pyRun code.pyImport + initialiseApplication loopRead → 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.
  1. Set up the ADC input and five-pixel output once.
  2. Capture one input reading.
  3. Calculate percentage from that captured reading.
  4. Compare the percentage with 50.
  5. Choose green or red, then transmit the colour to the LED chain.
  6. 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.
Working valueCurrent state
Fixed threshold50.0%
Captured API reading—
Calculated percentage—
Selected colour in bufferOFF
Physical pixel 0OFF

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 constructSoftware effectHardware consequence
import and constructorsLoad dependencies and create input/output objectsInitialise the interfaces; perform setup outside the repeating loop.
reading = pot.valueStore one returned measurementRead the GP28 ADC input. Later calculations use this stored value.
percent = reading * 100 / 65535Calculate a new numberNo output changes merely because arithmetic runs.
if … elseExecute one colour-selection branchSpecify the desired output based on the requirement.
pixels[0] = …Modify the first pixel’s buffered colourWait for show() because auto_write is disabled.
pixels.show()Transfer the buffered pixel dataUpdate the WS2812 chain using GP14.
time.sleep(0.1)Pause this application’s execution for approximately 100 msNo fresh input read occurs in this loop during the pause; the existing LED colour remains.
finallyRun cleanup on exit from the try blockRequest 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,535p = 100 × 16,388 ÷ 65,535p ≈ 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,535p = 100 × 49,164 ÷ 65,535p ≈ 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 + TsleepTloop = 0.010 s + 0.100 sTloop = 0.110 sfs = 1 ÷ Tloopfs = 1 ÷ 0.110 sfs ≈ 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 categoryExample symptomUseful first check
Syntax / indentationThe interpreter reports a syntax or indentation errorCheck the reported line, colons and block indentation.
Runtime / dependencyThe program stops during an import or hardware setupRead the traceback; check the library name/version and pin ownership.
LogicCode runs but green appears below the thresholdTrace the comparison and the two branch assignments against the requirement.
Timing / samplingAn input change seems to have a delayed effectIdentify when the last reading was captured and what work delays the next read.
Interface / output updateThe buffered colour changes but the LED does notCheck 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

CLO1 (C4): Understand → Apply → Analyse. Formal CLO2 hardware/programming assessment follows Chapter 5.

1. Which statement best describes firmware?

CLO1 · Bloom: Understand

2. What role does Thonny play in this course?

CLO1 · Bloom: Understand

3. An input API reading is 16388. What colour does the worked program select?

CLO1 · Bloom: Apply

4. With auto_write=False, which operation transfers the selected pixel colour?

CLO1 · Bloom: Apply

5. The knob changes after reading is assigned but before the comparison. The comparison uses…

CLO1 · Bloom: Analyse

6. A loop sleeps for 0.1 s and also performs input, computation and output. Which conclusion is justified?

CLO1 · Bloom: Analyse

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.2 Getting started and core syntax

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.

  1. What is CircuitPython?
  2. Program structure, comments, and imports
  3. Variables, constants, and data types
  4. Operators and calculations

CHAPTER 4 / SUBTOPIC 4.2.1

4.2.1 What is CircuitPython?

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 goalUnderstand how a CircuitPython program runs on the EDU PICO.
Syntax: smallest CircuitPython program
print(VALUE)

# Example
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.

  1. Connect the EDU PICO by USB.
  2. Copy the required libraries into CIRCUITPY/lib.
  3. Rename one tutorial file to code.py.
  4. Save it to CIRCUITPY.
  5. Use the serial console to read print() output and errors.
print("Hello, EDU PICO!")
Hello, EDU PICO!
Hardware ruleEDU 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.

ModuleHardwareVerified GPIO / bus
01Push buttonsA GP0, B GP1
02Five WS2812 LEDsGP14
03AHT20 temperature/humidityI2C SDA GP4, SCL GP5
04APDS9960 proximityI2C SDA GP4, SCL GP5
05APDS9960 lightI2C SDA GP4, SCL GP5
06APDS9960 gestureI2C SDA GP4, SCL GP5
07APDS9960 colourI2C SDA GP4, SCL GP5
08PDM microphoneClock GP3, data GP2
09PotentiometerADC GP28
10Audio and buzzerAudio GP20, buzzer GP21
11SD cardMISO16, CS17, SCK18, MOSI19
12Flash-log switchGP15
13Servo and potentiometerServo GP6, ADC GP28
14Two DC-motor channelsGP10–GP13
15USB power relayGP22
16Capacitive keypadPico TX GP20, RX GP21
1728BYJ-48 stepperGP26, GP27, GP8, GP7
18TM1650 four-digit displayI2C SDA GP4, SCL GP5
InstallationCopy the complete Tutorials/lib directory to CIRCUITPY/lib. The included libraries are the verified CircuitPython 10 set used by these lessons.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is CircuitPython?

Bloom: Remember

2. What is the role of CircuitPython firmware on the EDU PICO?

Bloom: Understand

3. What is commonly the main application filename on a CircuitPython board?

Bloom: Remember

4. What can change while the EDU PICO hardware remains the same?

Bloom: Understand

5. How does CircuitPython normally execute application statements?

Bloom: Understand

6. Why is CircuitPython useful for introductory embedded development?

Bloom: Analyze

Not checked yet

CHAPTER 4 / SUBTOPIC 4.2.2

4.2.2 Program structure, comments, and imports

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 goalRecognise the main parts of a CircuitPython program.
Syntax: imports, comments, and blocks
import MODULE
from MODULE import NAME
# This is a one-line comment.

while CONDITION:
    INDENTED_STATEMENT
# Import modules that provide extra features.
import time
import board
import digitalio

# Create and configure a hardware object.
led = digitalio.DigitalInOut(board.LED)
led.direction = digitalio.Direction.OUTPUT

# Repeat forever.
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.
ImportantUse four spaces for each indentation level. Incorrect indentation causes an IndentationError.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What does an import statement do?

Bloom: Remember

2. What begins a Python single-line comment?

Bloom: Remember

3. Where should a hardware object usually be created for a continuously running program?

Bloom: Understand

4. What happens if the program imports a module that is not installed?

Bloom: Apply

5. Which ordering is clearest for a small hardware program?

Bloom: Analyze

6. What does `import time` provide?

Bloom: Understand

Not checked yet

CHAPTER 4 / SUBTOPIC 4.2.3

4.2.3 Variables, constants, and data types

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 goalStore values and choose suitable data types.
Syntax: variable assignment
variable_name = VALUE
CONSTANT_NAME = VALUE

# Update an existing variable
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"   # str: text
counter = 0                # int: whole number
voltage = 2.75             # float: decimal number
button_pressed = False     # bool: True or 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.

TypeExampleUse 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 itChange voltage to 3.3, add another variable called percentage, and print both values.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. Which type is returned by a digital input state?

Bloom: Remember

2. What type is 1.65?

Bloom: Remember

3. What is the usual Python convention for a constant name?

Bloom: Understand

4. What does `type(pot.value)` help identify?

Bloom: Apply

5. Why store 3.3 in a named constant such as VREF?

Bloom: Analyze

6. If `pressed = False`, what is the type of pressed?

Bloom: Remember

Not checked yet

CHAPTER 4 / SUBTOPIC 4.2.4

4.2.4 Operators and calculations

Definition

An operator performs arithmetic, comparison, Boolean, or membership operations on values.

Source topic: 4. Operators and calculations

Learning goalCalculate 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is 17 // 5?

Bloom: Apply

2. What does 17 % 5 return?

Bloom: Apply

3. Which operator compares two values for equality?

Bloom: Remember

4. What is evaluated first in `3 + 4 * 2`?

Bloom: Understand

5. Which expression combines two conditions logically?

Bloom: Apply

6. Why add parentheses to an ADC voltage expression?

Bloom: Analyze

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.3 Decisions, repetition, and collections

Learning goal

Choose actions, repeat operations, and organize related values.

The following lessons reproduce the complete Programming Fundamentals sequence from the course reference, including explanations, code examples, interactives, project, and practice material.

  1. Decisions with if, elif, and else
  2. Switch choices in CircuitPython
  3. Repetition with while and for loops
  4. Arrays and other collections

CHAPTER 4 / SUBTOPIC 4.3.1

4.3.1 Decisions with if, elif, and else

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 goalMake 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. Which keyword begins a decision?

Bloom: Remember

2. When does elif run?

Bloom: Understand

3. What does else represent?

Bloom: Remember

4. If temp is 36, which branch in the example runs?

Bloom: Apply

5. Why place the 35-degree test before the 25-degree test?

Bloom: Analyze

6. What does indentation show after `if ready:`?

Bloom: Understand

Not checked yet

CHAPTER 4 / SUBTOPIC 4.3.2

4.3.2 Switch choices in CircuitPython

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 goalSelect one action from many choices.
Syntax: switch-compatible alternatives
# Alternative 1: decision chain
if selection == VALUE_1:
    ACTION_1
elif selection == VALUE_2:
    ACTION_2
else:
    DEFAULT_ACTION

# Alternative 2: dictionary lookup
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

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is a switch-like choice used for?

Bloom: Understand

2. Which constructs does the source teach for switch-like behavior?

Bloom: Remember

3. What does a dictionary lookup map?

Bloom: Understand

4. What is the benefit of `mapping.get(key, default)`?

Bloom: Apply

5. When is an if/elif chain a clear choice?

Bloom: Apply

6. What should a program do for an unrecognized selection?

Bloom: Analyze

Not checked yet

CHAPTER 4 / SUBTOPIC 4.3.3

4.3.3 Repetition with while and for loops

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 goalRepeat 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):          # 0, 1, 2, 3, 4
    print(number)

for angle in range(0, 181, 10): # 0 to 180, step 10
    set_angle(angle)
Avoid accidental busy loopsA 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

2. When does a while loop test its condition?

Bloom: Understand

3. What is a common cause of an unintended infinite loop?

Bloom: Analyze

4. Which loop suits processing every item in a list?

Bloom: Apply

5. Why might an embedded main loop use while True?

Bloom: Understand

6. What does `break` do in a loop?

Bloom: Remember

Not checked yet

CHAPTER 4 / SUBTOPIC 4.3.4

4.3.4 Lists, Tuples, Dictionaries and Typed Arrays

Definition

A collection stores multiple related values; its type determines how values are organized and accessed.

Source topic: 8. Arrays and other collections

Learning goalStore 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

2. Which collection is immutable?

Bloom: Remember

3. What does `value in items` test?

Bloom: Understand

4. Which is suitable for a fixed stepper phase sequence?

Bloom: Apply

5. What is `values[1:3]` for [4, 8, 12, 16]?

Bloom: Apply

6. Why use a typed array for many same-kind numeric samples?

Bloom: Analyze

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.4 Functions, hardware access, and reliability

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.

  1. Functions, parameters, return values, and scope
  2. Modules, objects, properties, and methods
  3. Timing: blocking and non-blocking programs
  4. Errors, exceptions, and cleanup
  5. Complete syntax used by the 18 hardware modules

CHAPTER 4 / SUBTOPIC 4.4.1

4.4.1 Functions, parameters, return values, and scope

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 goalOrganise 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 guidelineA 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
12

Example 2: default parameter

Syntax
def function_name(parameter=default_value):
    return result
Explanation

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.50

Example 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
None

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What does `def` begin?

Bloom: Remember

2. What is a parameter?

Bloom: Understand

3. What does return voltage do?

Bloom: Apply

4. Where is a local variable normally available?

Bloom: Understand

5. What does a function with no return return by default?

Bloom: Remember

6. Why use a helper function for ADC conversion?

Bloom: Analyze

Not checked yet

CHAPTER 4 / SUBTOPIC 4.4.2

4.4.2 Modules, objects, properties, and methods

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 goalUnderstand 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) # SCL, SDA

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
3

Example 2: create an object and call a method

Syntax
object_name = ClassName(arguments)
object_name.method(arguments)
value = object_name.property
Explanation

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
1

Example 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is a module?

Bloom: Remember

2. In the example, what is `led`?

Bloom: Understand

3. What is `led.value`?

Bloom: Apply

4. What does `led.deinit()` illustrate?

Bloom: Understand

5. Why call deinit when finished with certain hardware objects?

Bloom: Analyze

6. What is the role of `import board`?

Bloom: Remember

Not checked yet

CHAPTER 4 / SUBTOPIC 4.4.3

4.4.3 Timing: blocking and non-blocking programs

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 goalChoose 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")

    # Other inputs can be checked here without waiting.

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.

ChallengeModify the button tutorial so it prints a sensor value every two seconds while still responding immediately to button presses.
Working example: module 17The 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
Done

Example 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 elapsed

Example 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What does a blocking sleep do?

Bloom: Remember

2. Which clock is suitable for measuring elapsed time?

Bloom: Apply

3. Why can a long blocking delay harm responsiveness?

Bloom: Analyze

4. What is a non-blocking timing pattern?

Bloom: Understand

5. What can hardware PWM do during a Python delay?

Bloom: Understand

6. Which change makes an interval from milliseconds to seconds?

Bloom: Apply

Not checked yet

CHAPTER 4 / SUBTOPIC 4.4.4

4.4.4 Errors, exceptions, and cleanup

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 goalRead 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
ErrorCommon 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 errorA 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_error
Explanation

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 number

Example 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
Cleanup

Example 3: distinguish normal and invalid input

Syntax
try:
    value = conversion(text)
except ValueError:
    handle_invalid_input
else:
    use_value
Explanation

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
Invalid

Examples 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 syntax
How 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 block
How 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 defined
How 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_library
Typical 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 initialized
How 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 found
How 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
KeyboardInterrupt
How to address it

Use try and finally to switch off outputs and release initialized hardware when the program stops.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is an exception?

Bloom: Remember

2. Which block contains code that may fail?

Bloom: Remember

3. Why catch a specific exception such as OSError?

Bloom: Analyze

4. When does finally execute?

Bloom: Understand

5. What is risky about `except: pass`?

Bloom: Analyze

6. What can `deinit()` do for a hardware object?

Bloom: Apply

Not checked yet

CHAPTER 4 / SUBTOPIC 4.4.5

4.4.5 Complete syntax used by the 18 hardware modules

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 goalRecognise 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]
SyntaxUse 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)
FormatMeaning
{}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 checkThis 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 V

Example 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):
    statements
Explanation

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 1

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What punctuation ends an if/for/def header?

Bloom: Remember

2. How are code blocks marked in Python?

Bloom: Remember

3. What does `.format(value)` do in a string template?

Bloom: Understand

4. In `PWMOut(pin, frequency=1000)`, what is frequency=1000?

Bloom: Apply

5. What should you consult to understand an unfamiliar library parameter?

Bloom: Analyze

6. What is a useful first step when tracing a program?

Bloom: Apply

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.5 Integrated mini-project

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.

  1. Combined mini-project: adjustable LED level

CHAPTER 4 / SUBTOPIC 4.5.1

4.5.1 Combined mini-project: adjustable LED level

Definition

An integrated project combines input, calculation, functions, decisions, repetition, and output control.

Source topic: 14. Combined mini-project: adjustable LED level

Learning goalCombine 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 itAdd 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

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What is the first operation in the mini-project?

Bloom: Remember

2. Why divide by 65535?

Bloom: Understand

3. At exactly 50%, what does `percent >= 50` evaluate to?

Bloom: Apply

4. What is a sensible debugging order?

Bloom: Analyze

5. What type is percent after division?

Bloom: Understand

6. What changes the LED state in the example?

Bloom: Apply

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.6 Interactive concept laboratory

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.

  1. Interactive concept laboratory

CHAPTER 4 / SUBTOPIC 4.6.1

4.6.1 Interactive concept laboratory

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 goalChange input values and immediately observe how the corresponding Python calculation behaves.

ADC converter

This uses the same formula as the potentiometer tutorial.

If–elif–else simulator

The result follows the temperature decision demonstrated earlier.

range() visualiser

Enter start, stop, and step values. Remember that stop is excluded.

List average calculator

Enter comma-separated sensor readings to simulate list processing.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What should you record in a prediction activity?

Bloom: Understand

2. Which first question helps trace a hardware program?

Bloom: Apply

3. Why change one interactive input at a time?

Bloom: Analyze

4. What can a slider model help explain?

Bloom: Understand

5. Where should hardware faults be checked in the program flow?

Bloom: Analyze

6. When will formal practical construction tasks be designed?

Bloom: Remember

Not checked yet

CHAPTER 4 / PROGRAMMING FUNDAMENTALS

4.7 Practice and quick reference

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.

  1. Practice tasks and quick reference

CHAPTER 4 / SUBTOPIC 4.7.1

4.7.1 Practice tasks and quick reference

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 goalApply each concept without copying a complete solution.
Syntax: plan before coding
# 1. Import required modules
# 2. Declare constants and variables
# 3. Create hardware objects
# 4. Define reusable functions
# 5. Run the main loop
# 6. Handle errors and clean up outputs
  1. Variables: Store your name, group number, and a target temperature. Print one formatted sentence.
  2. If–else: Print LOW, MEDIUM, or HIGH for three potentiometer ranges.
  3. For loop: Make each WS2812 LED turn on one at a time.
  4. While loop: Count button presses until the count reaches ten.
  5. Collection: Store five temperature readings in a list and calculate their average.
  6. Function: Write celsius_to_fahrenheit(celsius) and return the answer.
  7. Dictionary: Map keypad values to the names ONE, TWO, and THREE.
  8. 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?

Six-question self-check

Assessment alignment: CLO1 · Bloom levels: Remember, Understand, Apply, and Analyze.

1. What should a programmer do before writing a program for a practice task?

Bloom: Apply

2. Which task practices a list and average calculation?

Bloom: Remember

3. Why test a program with more than one input value?

Bloom: Analyze

4. Which is a suitable quick-reference habit?

Bloom: Understand

5. What does the practice checklist help verify?

Bloom: Apply

6. When should practical construction tasks be assembled for this course?

Bloom: Remember

Not checked yet

CHAPTER 05

Hardware Components

YOUR LEARNING GOALS

Chapter 5 learning outcomes

By the end of this chapter, students should be able to:

  1. Distinguish microcontrollers from microprocessors and compare RISC/CISC and Harvard/Von Neumann architecture concepts.
  2. Explain the roles of the control unit, ALU, registers, and bus interfaces, and trace the fetch–decode–execute cycle.
  3. Interpret data, address, and control paths; calculate memory capacity from a stated address organization; and interpret little-endian and big-endian byte sequences.
  4. Explain the roles of boot ROM, external flash, and SRAM in an RP2040 system, distinguishing stored firmware and Python files from runtime data.
  5. Select GPIO, UART, SPI, or I²C for a stated device connection and interpret a basic interface timing diagram.
  6. Calculate timing intervals from stated clock and counting parameters, distinguish software timing from hardware timer/PWM operation, and explain the role of a watchdog.
  7. 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.

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

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.

CPUfetch · decode · executeProgram & dataFlash · SRAMInput & outputGPIO · ADC · UART · I²CClock & resetConceptual 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 pointMicrocontrollerMicroprocessor
Typical integrationCPU, memory and peripheral blocks integrated in a control-oriented chip.CPU-centered IC commonly paired with external memory and I/O support.
Typical useDedicated sensing, control and embedded applications.General-purpose computing or larger systems.
Course exampleRP2040 on EDU PICO.A processor used in a computer or application processor system.
Main design trade-offCompact 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 ideaRISC tendencyCISC tendency
Instruction setOften a smaller, more regular collection of basic operations.Often a richer collection, including more complex operations.
Work per instructionA task may be expressed as several simple instructions.Some tasks may be expressed with fewer, more elaborate instructions.
Memory operationsCommonly uses separate load/store instructions; arithmetic operates on registers.Some architectures allow instructions to operate directly on memory operands.
Design emphasisRegular 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 C

A 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

LevelWhat it describesRP2040 course example
BoardThe complete teaching platform and its connections.EDU PICO connects the RP2040 to flash, power circuitry, and learning devices.
SoCThe integrated chip containing processor cores and hardware blocks.RP2040 is an SoC with two Arm Cortex-M0+ cores, SRAM, GPIO, and peripheral controllers.
Processor / ISAThe 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.

ComponentQuestion it answersEDU PICO example
CPUWhat operation should happen next?Execute runtime instructions that interpret the program and compare a reading with a threshold.
MemoryWhat instructions and values are available?Flash stores firmware and files; SRAM holds live sensor values and display buffers.
I/O subsystemHow does information enter or leave?GP28 feeds the ADC; GP14 sends NeoPixel data; the I²C controller communicates with sensors and OLED.
System interconnectHow 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. Which description best distinguishes a microcontroller from a microprocessor?

Bloom: Understand

2. The RP2040 contains two Cortex-M0+ processor cores. What does “dual-core” mean?

Bloom: Remember

3. The term “32-bit processor” primarily describes the processor’s…

Bloom: Understand

4. A loop performs 500 iterations and takes 4 μs per iteration in an idealized timing model. Estimated time?

Bloom: Apply

5. Why is RISC/CISC a useful comparison but insufficient to choose a board by itself?

Bloom: Analyse

6. Which statement about the RP2040 is accurate?

Bloom: Remember

Not checked yet

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 ÷ fT = 1 ÷ 125,000,000 HzT = 8 × 10-9 sT = 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 ÷ ftCPU = 2,000,000 ÷ 125,000,000 stCPU = 0.016 stCPU = 16 ms

Interpretation: This ideal estimate excludes additional waits and runtime work.

CHAPTER 5 / SUBTOPIC 5.2

5.2 Hardware model

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?

CPUfetch · decode · executeProgram & dataFlash · SRAMInput & outputGPIO · ADC · UART · I²CClock & resetConceptual 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 modelQuestion it answersExample
AddressWhich location or peripheral register?Choose a memory byte or a peripheral register.
DataWhat value is transferred?A sensor code, instruction word, or output setting.
ControlWhat 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^

16 = 65,536 byte

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.

TransactionAddress pathData pathControl meaning
Instruction fetchSelect the instruction location.Read instruction bits into the processor.Read/fetch; wait for the response when required.
Read working dataSelect the relevant SRAM location.Transfer the stored value to the processor.Read operation.
Write working dataSelect the destination SRAM location.Transfer the new value from the processor.Write operation.
Access a peripheralSelect 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. In a simplified computer model, which block executes instructions and coordinates system activity?

Bloom: Remember

2. Which bus conceptually carries the location of a memory or I/O item to be accessed?

Bloom: Understand

3. Which path carries the value read from or written to a selected location?

Bloom: Understand

4. Why should the classic address/data/control bus diagram be treated as a model for RP2040?

Bloom: Analyse

5. A system has 16 address bits and addresses individual bytes. Its theoretical addressable capacity is…

Bloom: Apply

6. What is the main purpose of a control path in the computer model?

Bloom: Understand

Not checked yet

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 = 2bL = 216L = 65,536B = L × wB = 65,536 × 1 byteB = 65,536 bytesB = 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 − 1Alast = 0x2000 + 0x2000 − 1Alast = 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

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 · Fetch
obtain instruction
→2 · Decode
identify operation
→3 · Execute
operate 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

ns = 16 ms

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.

RP2040 · Two processor cores on one chipCore 0 · Cortex-M0+Fetch / decodeControl logicRegisters R0–R15+ xPSRNVIC / exceptions32-bit ALUAHB-Lite interfaceCore 1 · Cortex-M0+Fetch / decodeControl logicRegisters R0–R15+ xPSRNVIC / exceptions32-bit ALUAHB-Lite interfaceShared AHB-Lite crossbarSRAM · 264 KBXIP → external flashAPB bridge → peripherals

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.

N · Negative0
Z · Zero0
C · Unsigned carry0
V · Signed overflow0

The trace illustrates data flow rather than separate clock cycles. Values and flags are simulated. CircuitPython integers are runtime objects; one Python addition need not execute as one ADDS instruction.

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

StageWhat changesStudent interpretation
FetchThe processor uses its instruction address to obtain instruction bits.The program counter identifies the instruction stream. Instruction bits are distinct from sensor data.
DecodeControl logic identifies the operation and operands.The CPU determines whether to add, compare, load, store or branch.
ExecuteRegisters, 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

Stack and instruction flow

Status and control

Selected register

R0

Illustrative example

Follow one addition

ADDS R2, R0, R1 adds 7 and 3. Step through the source registers, destination and condition flags.

R0 · 7R1 · 3
ALU
R2 · 10APSR · N/Z/C/V

These are teaching examples, not live register readings. SP points into a stack in memory; LR holds return information; PC tracks instruction execution. Python variable names are not permanently assigned to R registers.

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 conceptFunctionRP2040 interpretation
R0–R12General-purpose working registers for values and addresses.Each Cortex-M0+ core has its own processor register state.
SP / R13Points to a stack location; it does not hold the entire stack.The stack itself occupies memory and supports calls and exception handling.
LR / R14Holds return-link information for calls and exception return.Function return is more than simply incrementing the program counter.
PC / R15Tracks the instruction address used by execution.Branches change the instruction path.
PSR / APSRRecords 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, conceptualHolds 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.

Addition32-bit resultFlags for this addition
0xFFFFFFFF + 0x000000010x00000000N=0, Z=1, C=1, V=0
0x7FFFFFFF + 0x000000010x80000000N=1, Z=0, C=0, V=1
0x0000004A + 0x000000790x000000C3N=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

Enter hexadecimal operands from 00000000 to FFFFFFFF. Compare unsigned carry with signed overflow using the presets.

Result (hex)Unsigned resultSigned result
0x0000000000
N=0 · Z=1 · C=1 · V=0

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. What is the ALU’s primary role?

Bloom: Remember

2. What does the control unit do during instruction execution?

Bloom: Understand

3. A CPU register is best defined as…

Bloom: Remember

4. During fetch–decode–execute, which action happens first for the next instruction?

Bloom: Understand

5. An idealized task needs 2,000,000 cycles at a 125 MHz clock. Its idealized duration is…

Bloom: Apply

6. Why is the idealized cycle-time calculation not always an exact measurement of Python program time?

Bloom: Analyse

Not checked yet

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 ÷ fT = 1 ÷ 125,000,000 HzT = 8 × 10-9 sT = 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 ÷ ftCPU = 2,000,000 ÷ 125,000,000 stCPU = 0.016 stCPU = 16 ms

Interpretation: This ideal estimate excludes additional waits and runtime work.

CHAPTER 5 / SUBTOPIC 5.2.2

5.2.2 System buses

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.

CalculationEquationWorked result
Address capacity2ⁿ addresses16-bit byte addressing → 2¹⁶ = 65,536 bytes = 64 KiB.
Bits to bytesbits ÷ 832-bit word → 4 bytes.
Ideal data ratebits per transfer × transfers/s32 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

2 · Choose the destination

Core 0AHB-LiteCore 1AHB-LiteDMA readAHB-LiteDMA writeAHB-LiteRP2040 AHB-Lite crossbar · 4 upstream / 10 downstream portsAddress decode routes requests; arbiters handle competing accesses.ROM1 portFlash XIP1 portSRAM 0–56 portsFast AHB-Lite1 portAPB bridge1 portCore 0 IOPORTCore 1 IOPORTSIOSeparate from main crossbar

Data direction:

Illustrative payload: —

Destinations are grouped: SRAM 0–5 represent six ports, giving ten downstream ports in total. Fast peripherals include PIO, USB and DMA control registers; APB serves lower-bandwidth peripherals. SIO is reached through processor IOPORTs, not the DMA crossbar route. The fixed 0x41 payload is simulated; steps are not individual clock cycles or real peripheral reads/writes.

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 = 2bB = 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 organizationCalculationResult
12 address bits, one byte per location2^12 = 4096 locations4 KiB; addresses 0x000–0xFFF
22 address bits, one byte per location2^22 = 4,194,304 locations4 MiB; addresses 0x000000–0x3FFFFF
13 address bits, two bytes per location8192 × 2 = 16,384 bytes8 Kiwords of 16-bit words = 16 KiB
32 KiB, byte-addressed32 × 1024 = 2^15 bytes15 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. How many bytes are in a 32-bit data word?

Bloom: Remember

2. A 32-bit byte-addressed address bus can represent how many unique addresses?

Bloom: Apply

3. What is 0x20000000 commonly used for in RP2040’s address map?

Bloom: Remember

4. Why is “data, address and control buses” still useful when RP2040 has a crossbar?

Bloom: Analyse

5. A memory contains 8192 addressable bytes. Minimum address bits required?

Bloom: Apply

6. A bus transfers 32 bits per transfer at 10 million transfers per second. Ideal data rate?

Bloom: Apply

Not checked yet

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 = 2bL = 216L = 65,536B = L × wB = 65,536 × 1 byteB = 65,536 bytesB = 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 − 1Alast = 0x2000 + 0x2000 − 1Alast = 0x3FFF

Interpretation: Subtract one because the first address is included in the block.

CHAPTER 5 / SUBTOPIC 5.2.3

5.2.3 Memory organization

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 resourceVolatile?Role in the course system
Boot ROMNoStartup and boot support.
External QSPI flashNoCircuitPython firmware and files such as code.py and libraries.
264 KiB SRAMYesRuntime variables, stack, buffers and active program data.
XIP cacheTemporary/cacheSpeeds access to recently read flash data.

Memory-capacity calculations

Worked calculation: capacity, address bits and endianness

264 KiB SRAM = 264 ×

1024 = 270,336 bytes

To address 270,336 bytes individually, choose n where 2^n ≥ 270,336. Since 2^

18 = 262,144

is too small and 2^

19 = 524,288

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.

Address + control → destinationCore 0 · Cortex-M0+AHB-Lite interfaceAHB-Lite crossbarSRAM40x12345678—Data direction follows the selected operation.Address:0x20040000Control:—
Word address · tap to select+0+1+2+332-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.

The 16 displayed bytes are simulated contents, not actual boot ROM, flash firmware or live SRAM. The SRAM example uses bank 4 (0x20040000–0x20040FFF); RP2040’s first 256 KiB SRAM region is word-striped across banks 0–3. SRAM4 and SRAM5 add 4 KiB each, giving 264 KiB total SRAM. Flash programming is a separate operation, so ordinary XIP writes are blocked here. This diagram illustrates access roles, not exact bus-cycle timing or CircuitPython object placement.

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

TypePower-off retentionHow it is used or changed
Mask ROMNon-volatileContents are established during manufacture.
OTP ROMNon-volatileOne-time programmable storage.
EPROMNon-volatileTraditional erasable devices use ultraviolet erasure and reprogramming.
EEPROMNon-volatileElectrically erasable/programmed; write timing and endurance depend on the device.
FlashNon-volatileTypically erase in blocks before programming; used for board firmware and files.
FRAMNon-volatileUses ferroelectric storage; characteristics depend on the selected chip.
SRAMVolatileFast working storage that needs power but no DRAM-style refresh; RP2040 uses SRAM.
DRAMVolatileRequires 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

SRAM1 · 64 KiB

SRAM2 · 64 KiB

SRAM3 · 64 KiB

Selected bank: SRAM0

Word index inside that bank: 0

Cortex-M0+ coreAHB-LiteRP2040 crossbar0x20000000SRAM064 KiBSRAM164 KiBSRAM264 KiBSRAM364 KiBSRAM44 KiBSRAM54 KiB

Try 0x20000000 → 0x20000004 → 0x20000008 → 0x2000000C → 0x20000010. The fifth word returns to SRAM0 at bank word index 1. SRAM4 and SRAM5 use direct, non-striped regions. Four × 64 KiB + two × 4 KiB = 264 KiB. Both cores and DMA can access these banks; a bank is not reserved to one core by hardware.

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.

Word bytes · most significant on the left

Most significant byteLeast significant byte

Little-endian · RP2040

Lowest addressIncreasing addresses →

Big-endian · comparison

Lowest addressIncreasing addresses →

Selected byte: · Bits:

Correctly reconstructed word (either order):

Endianness changes byte placement, not the order of bits inside each byte. Both rows represent the same value when decoded using their own byte order. A communication protocol may use a different byte order from the processor. Addresses here illustrate SRAM4; no actual memory is read or written.

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.

AddressLittle-endian: 0x12345678Big-endian: 0x12345678
0x200400000x780x12
0x200400010x560x34
0x200400020x340x56
0x200400030x120x78

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.

Core 0 · Cortex-M0+AHB-LiteShared crossbarXIP / cacheExternal flashSRAMCan hold code and data0x10000000 · XIP0x20000000 · SRAMOne main memory interface per coreQSPI

Selected address: 0x10001000

Instruction fetch, load and store use each core’s main AHB-Lite memory port. SRAM may contain machine code as well as data; XIP maps external flash into the address space and caches reads. Cache hits can return data without a new external flash transaction. SIO and other bus masters are omitted here.

The trace is a conceptual read transaction, not a cycle-accurate simulation. Addresses are illustrative locations, not actual firmware listings. The core fetches machine instructions used by the CircuitPython runtime; one Python statement is not one machine instruction.

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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. Which memory loses its contents when power is removed?

Bloom: Remember

2. Which RP2040 memory is non-volatile and commonly stores firmware and files?

Bloom: Understand

3. The RP2040 has 264 KiB of on-chip SRAM. How many bytes is this using 1 KiB = 1024 bytes?

Bloom: Apply

4. A stored 32-bit value 0x12345678 appears in little-endian byte order as…

Bloom: Apply

5. How many address bits are needed to uniquely address each byte in 264 KiB SRAM, ignoring address-map gaps?

Bloom: Apply

6. Which statement correctly compares program storage and runtime variables in the EDU PICO?

Bloom: Understand

Not checked yet

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 = 2bL = 216L = 65,536B = L × wB = 65,536 × 1 byteB = 65,536 bytesB = 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 − 1Alast = 0x2000 + 0x2000 − 1Alast = 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

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.

InterfaceTiming calculation students can performExample
GPIO / ADCADC code-to-voltage and threshold comparison.A changing potentiometer voltage.
UARTFrame bits ÷ baud = approximate frame time.8-N-1 sends 10 bits per data byte.
I²CClock count × SCL period; include address/data ACK bits.Two bytes need at least 18 SCL pulses.
SPIBits ÷ (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 partRoleExample
Control/configurationChoose operating mode and timing.UART baud rate; ADC channel; GPIO direction.
StatusReport readiness or completion.Received data available; conversion complete.
Data register / FIFOHold values waiting to be transferred or consumed.UART transmit/receive buffers.
External signal logicProduce 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.

EDU PICO UARTUART peerCPU / CircuitPythonPeer applicationTX buffer—RX buffer—TX buffer—RX buffer—TXRXTXRXCommon GNDGP20 TX / GP21 RX3.3 V logic
HIGH / 1LOW / 0IdleIdle

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 statementRole and effect
import board / busioboard supplies pin names; busio supplies the hardware UART class.
tx=board.GP20 / rx=board.GP21Select transmit and receive pins from the EDU PICO UART wiring used in the course.
baudrate=9600Request 9600 transmitted bit intervals per second; this is not 9600 data bytes per second.
bits=8, parity=None, stop=1Eight data bits, no parity bit, one stop bit. Start/stop framing makes ten bit intervals per byte.
timeout=0.01Read timeout in seconds: up to about 10 ms when the requested data is not available.
receiver_buffer_size=64Request 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_waitingNumber 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 uartCreate 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

Parallel transfer places several data bits on separate paths; serial transfer sends a sequence of bits over fewer data paths.
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.

Single signalMulti-bit bus0x410xE1InvalidChangeTime → (conceptual intervals)

Single-signal state:

Bus state:

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.

R/WEnable (LOW)Address busData bus0x20000x41SetupHoldSample: 70 ns01020507090100ns

Data direction:

Data becomes valid (ns):

Available setup / hold (ns):

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 termMeaning
Setup timeMinimum time data must already be stable before the sampling event.
Hold timeMinimum time data must remain stable after the sampling event.
Access / propagation timeDelay from a request or input change until the corresponding output becomes valid.
Chip select / enableIdentifies 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. Which interface is typically used by the course AHT20 sensor with clock and data lines?

Bloom: Remember

2. A UART sends 8-N-1 framing. How many transmitted bits are needed for each 8-bit data byte?

Bloom: Apply

3. At 9600 baud, ideal time to send one 10-bit UART frame is approximately…

Bloom: Apply

4. An I²C address byte plus one data byte requires how many clock pulses before considering START/STOP timing?

Bloom: Apply

5. Which description fits SPI?

Bloom: Understand

6. A 128-byte display transfer over a 400 kHz I²C bus has at least how much raw byte-clock time, ignoring address/ACK/control overhead?

Bloom: Analyse

Not checked yet

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 ÷ fbustframe = 10 ÷ 115,200 stframe ≈ 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 × 9Nbits = 6 × 9Nbits = 54tframe = Nbits ÷ fbustframe = 54 ÷ 100,000 stframe = 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 ÷ fbustframe = 8 ÷ 1,000,000 stframe = 8 µs

Interpretation: This excludes chip-select and command overhead.

CHAPTER 5 / SUBTOPIC 5.3

5.3 RP2040 hardware structure

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.

CPUfetch · decode · executeProgram & dataFlash · SRAMInput & outputGPIO · ADC · UART · I²CClock & resetConceptual 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

FromToCalculation
Frequency to periodHz → secondsT = 1/f. At 125 MHz, T = 8 ns.
Cycles to timecycles → secondst = N/f. 2 million cycles at 125 MHz → 16 ms.
Period to rateseconds → Hzf = 1/T. A 20 ms period → 50 Hz.
Samples per intervalsamples, seconds → samples/srate = 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

Official RP2040 system overview: cores, bus fabric, memory, clocks and peripheral blocks.
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 resourceRP2040 capabilityConnection to the course
Processor coresTwo 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.
SRAM264 KiB across six physical banks.Runtime objects, stacks and buffers share this finite working space.
GPIO / ADC30 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 controllersTwo UART, two SPI and two I²C controllers.EDU PICO I²C examples use GP5 SCL and GP4 SDA.
PWMEight 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 / watchdogElapsed-time/alarm hardware and a separate recovery watchdog.Distinguish measurement, waveform generation and recovery.
PIO / DMAProgrammable 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. What is the nominal system clock commonly used by RP2040 boards such as Pico in their standard configuration?

Bloom: Remember

2. Which resource generates RP2040’s global microsecond timebase?

Bloom: Remember

3. Which RP2040 resources can also provide counting/timing functions besides the system timer?

Bloom: Understand

4. If clk_sys is 125 MHz, one ideal system-clock period is…

Bloom: Apply

5. Why should an RP2040 block diagram show clock and reset/control alongside CPU, memory and I/O?

Bloom: Understand

6. Which statement best describes a system-on-chip architecture?

Bloom: Remember

Not checked yet

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 ÷ Tf = 1 ÷ 0.0000025 sf = 400,000 Hzf = 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 × tNcycles = 125,000,000 Hz × 0.001 sNcycles = 125,000

Interpretation: This is clock cycles, not necessarily instructions.

CHAPTER 5 / SUBTOPIC 5.3.1

5.3.1 Program and data memory

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 ROMStartup supportOn-chip · persistentExternal flashFirmware + CIRCUITPY filesBoard-level · persistent264 KiB SRAMObjects · stack · buffersOn-chip · volatileCPU + 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 calculateBasic equationMeaning 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 − 1C = 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 = 0Anext = ceil(A ÷ S) × Spadding = 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

  1. Identify what is given and what is required: capacity, remaining bytes, address bits, last address, alignment or buffer size.
  2. Write the values with units. Convert KiB or MiB to bytes before combining them; state the stored word/sample width.
  3. Choose and write the basic equation. Substitute the values, then calculate.
  4. Check rounding and endpoints: round address-bit requirements upward, use +1 for inclusive ranges, and check the alignment remainder.
  5. 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 × 1024B = 264 × 1024B = 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,576C = 2,097,152 bytesU = 1.5 × 1,048,576U = 1,572,864 bytesR = 0 bytes

3. Subtract used and reserved space

F = C − U − RF = 2,097,152 − 1,572,864 − 0F = 524,288 bytesF = 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,576C = 2,097,152220 = 1,048,576221 = 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 × 1024C = 270,336218 = 262,144219 = 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 ÷ 8S = 32 ÷ 8S = 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 4A mod S = 3P = S − (A mod S)P = 4 − 3P = 1 byteAnext = A + PAnext = 0x20040003 + 0x1Anext = 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 × SA0 = 0x20040004 + 0x0A0 = 0x20040004A1 = 0x20040004 + 0x4A1 = 0x20040008A2 = 0x20040004 + 0x8A2 = 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

RegionAddress or rangeInterpretation
Boot ROM base0x00000000On-chip startup and support routines.
Main XIP window base0x10000000Mapped reads from external flash; the installed flash chip determines physical capacity.
Standard SRAM window0x20000000–0x20041FFF264 KiB; includes the striped main banks and two smaller banks.
APB peripheral base0x40000000Peripheral control/status registers, not ordinary file storage.
AHB-Lite peripheral base0x50000000Additional mapped peripheral blocks.
SIO base0xD0000000Single-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 + 1B = 0x20041FFF − 0x20000000 + 1B = 0x42000B = 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.

One software address viewSix physical banks256 KiB striped region0x20000000–0x2003FFFFSuccessive words → banks 0–3SRAM0 · 64 KiBSRAM1 · 64 KiBSRAM2 · 64 KiBSRAM3 · 64 KiB0x20040000–0x20040FFFSRAM4 · 4 KiB0x20041000–0x20041FFFSRAM5 · 4 KiB4 × 64 KiB + 2 × 4 KiB = 264 KiB

Selected address: 0x20000000 · Physical bank: SRAM0 · Local word index: 0

The boxes are not drawn to capacity scale. Word striping routes a complete 32-bit word to one bank; it does not put each byte in a different bank. Both cores share the same physical SRAM. Alternative non-striped aliases for banks 0–3 are omitted and do not add storage.

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 × 1024B = M × 10242

2. Convert each quantity

32 KiB = 32 × 1024 bytes32 KiB = 32,768 bytes264 KiB = 264 × 1024 bytes264 KiB = 270,336 bytes2 MiB = 2 × 10242 bytes2 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 − RR = 0 MiB

2. Subtract the occupied space

F = 4 MiB − 2.75 MiB − 0 MiBF = 1.25 MiB

3. Convert the answer into bytes

F = 1.25 × 10242 bytesF = 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 × 10242C = 4,194,304 bytes222 = 4,194,304b = 22 bits

2. Find the minimum width for 264 KiB

C = 264 × 1024C = 270,336 bytes218 = 262,144 < 270,336219 = 524,288 ≥ 270,336b = 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 + 1B = 0x20041FFF − 0x20000000 + 1B = 0x42000 bytesB = 270,336 bytesB = 264 KiB

2. Find the last address in the 4 KiB bank

4 KiB = 4 × 1024 = 4096 = 0x1000 bytesAlast = Afirst + B − 1Alast = 0x20040000 + 0x1000 − 1Alast = 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 bytes0x20040003 mod 4 = 3P = 4 − 3 = 1 byteAaligned = 0x20040003 + 1Aaligned = 0x20040004

2. Find the sixth word start

k
— zero-based word index; the sixth word has k = 5
A5 = Aaligned + 5 × SA5 = 0x20040004 + 5 × 4A5 = 0x20040018

3. Find the last byte occupied by all six words

Bsix = 6 × 4 bytes = 24 bytesAlast = Aaligned + Bsix − 1Alast = 0x20040004 + 24 − 1Alast = 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 ÷ 8S = 16 ÷ 8S = 2 bytes/sample

2. Calculate raw data size

N
— number of samples
Braw
— raw packed sample-data size in bytes
Braw = N × SBraw = 1024 × 2Braw = 2048 bytesBraw = 2048 ÷ 1024Braw = 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 × 1024C = 2048 KiBU = 640 + 768U = 1408 KiBR = 32 KiB

2. Subtract used and reserved capacity

F = C − U − RF = 2048 − 1408 − 32F = 608 KiB

3. Convert free space into bytes

F = 608 × 1024 bytesF = 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 KiBBtotal = 256 KiB + 8 KiBBtotal = 264 KiBBtotal = 264 × 1024Btotal = 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 bytesA = Abase + w × SA = 0x20000000 + 7 × 4A = 0x2000001C

3. Find physical bank and local word index

physical bank = w mod 4physical bank = 7 mod 4 = SRAM3local 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. What is the boot ROM used for at startup?

Bloom: Understand

2. Why can RP2040 execute code from external flash without first copying all code to SRAM?

Bloom: Understand

3. How many bytes are in 264 KiB SRAM?

Bloom: Apply

4. A 2 MiB flash device stores files totaling 1.5 MiB. Nominal remaining capacity?

Bloom: Apply

5. Which memory is best suited to a rapidly changing variable while code is running?

Bloom: Understand

6. Why should students not assume every EDU PICO board has the same flash size?

Bloom: Analyse

Not checked yet

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 × BsampleBtotal = 1000 × 2 bytesBtotal = 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 × tNs = 100 samples/s × 10 sNs = 1000Btotal = Ns × BsampleBtotal = 1000 × 2 bytesBtotal = 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

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 × 106Atarget = (Anow + N) mod 232
  1. Given interval = 250 ms, timer tick = 1 μs and current low timer word = 8,000,000 μs.
  2. Convert the interval:

    t
    elapsed time or duration (s unless otherwise stated)
    t = 250 ÷ 1000= 0.250 s
  3. Substitute:

    N
    number of timer ticks
    N = 0.250 × 1,000,000= 250,000 ticks

    Each tick is one microsecond.

  4. Add the delay: 8,000,000 + 250,000 = 8,250,000 μs.
  5. 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
  1. 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 sftick = 1,000,000 ticks/s
  2. 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
  3. Substitute and calculate.
    N
    number of timer ticks
    N = 0.375 × 1,000,000= 375,000
  4. 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
  1. Identify values and convert units.
    Ttick
    duration of one timer tick (s)
    N
    number of timer ticks
    N = 2,400,000Ttick = 0.000001 s
  2. Write the equation.
    Ttick
    duration of one timer tick (s)
    Δt
    elapsed time interval (s)
    N
    number of timer ticks
    Δt = N × Ttick
  3. Substitute and calculate.
    Δt
    elapsed time interval (s)
    Δt = 2,400,000 × 0.000001= 2.4 s
  4. 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
  1. Identify values and convert units.
    Anow
    current timer count
    delay
    requested delay in the stated time/count unit
    Anow = 12,000,000 μsdelay = 80 ms= 80,000 μs
  2. 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
  3. 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
  4. 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
  1. Identify values and convert units.
    Atarget
    target timer count
    Anow
    current timer count
    Anow = 5,000,000Atarget = 5,250,0001000 μs = 1 ms
  2. 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
  3. Substitute and calculate.
    Ntick
    number of timer ticks
    Ntick = 5,250,000 − 5,000,000= 250,000delayms = 250,000 ÷ 1000= 250
  4. 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 − 1T = 1 ÷ fPWM
  1. 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.

  2. Convert units:

    fsys
    system-clock frequency (Hz)
    fsys = 125,000,000 Hz

    and

    fPWM
    PWM output frequency (Hz)
    fPWM = 20,000 Hz
  3. Find counts:

    C
    counter counts per PWM period
    C = 125,000,000 ÷ (1 × 20,000)= 6250

    counts per period.

  4. The counter includes zero, so

    TOP
    PWM counter upper limit (count)
    C
    counter counts per PWM period
    TOP = C − 1= 6250 − 1= 6249
  5. Check the setting: 0 ≤ 6249 ≤ 65,535, so TOP fits the 16-bit counter.
  6. Verify frequency:

    factual
    realized frequency (Hz)
    factual = 125,000,000 ÷ [1 × (6249 + 1)]= 20,000 Hz
  7. 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
  1. Identify values and convert units.
    fsys
    system-clock frequency (Hz)
    D
    PWM clock-divider setting (dimensionless; not duty percentage)
    fsys = 125,000,000 HzD = 5
  2. 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
  3. Substitute and calculate.
    fcounter
    PWM counter clock (Hz)
    fcounter = 125,000,000 ÷ 5= 25,000,000 Hz
  4. 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
  1. 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 HzD = 5fPWM = 10,000 Hz
  2. 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
  3. Substitute and calculate.
    TOP
    PWM counter upper limit (count)
    TOP = 125,000,000 ÷ (5 × 10,000) − 1= 2500 − 1= 2499
  4. 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
  1. 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 HzD = 2TOP + 1 = 12,500
  2. 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)]
  3. Substitute and calculate.
    fPWM
    PWM output frequency (Hz)
    fPWM = 125,000,000 ÷ (2 × 12,500)= 5000 Hz
  4. 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
  1. 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,250D = 4fsys = 125,000,000 Hz
  2. 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
  3. 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
  4. 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 ÷ 100u ≈ round(r × 65,535)
  1. Given duty = 40% and the API maximum = 65,535.
  2. Convert percent to a fraction:

    r
    dimensionless ratio in PWM calculations; CircuitPython ADC reading in ADC calculations
    r = 40 ÷ 100= 0.40
  3. Scale: 0.40 ×

    65,535 = 26,214.0

    . Round to the integer

    u
    integer CircuitPython duty setting, from 0 to 65,535
    u = 26,214
  4. 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 ÷ ffcounter = fsys ÷ DC = fcounter × TTOP = C − 1compare ≈ round(fcounter × TON)
  1. 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
  2. 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
  3. 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
  4. Find counter rate:

    fcounter
    PWM counter clock (Hz)
    fcounter = 125,000,000 ÷ 64= 1,953,125

    counts/s.

  5. 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
  6. Check the choice: TOP fits 16 bits.

    factual
    realized frequency (Hz)
    factual = 1,953,125 ÷ 39,062≈ 50.00064 Hz
  7. Pulse counts = 1,953,125 ×

    0.0015 = 2929.6875

    ; round to

    compare
    PWM HIGH compare count
    compare = 2930

    counts.

  8. 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
  1. 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 μsT = 12 μsuse matching units
  2. 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
  3. Substitute and calculate.
    p
    percentage on a 0–100 scale (%)
    p = 3 ÷ 12 × 100= 25%
  4. 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
  1. 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 = 35T = 40 μs
  2. 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
  3. Substitute and calculate.
    TON
    HIGH time within one period (same time unit as T)
    TON = 35 ÷ 100 × 40= 14 μs
  4. 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
  1. Identify values and convert units.
    TOP
    PWM counter upper limit (count)
    p
    percentage on a 0–100 scale (%)
    p = 30TOP + 1 = 1000
  2. 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))
  3. Substitute and calculate.
    compare
    PWM HIGH compare count
    round
    round to the nearest integer
    compare ≈ round(0.30 × 1000)= 300
  4. 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
  1. Identify values and convert units.
    u
    integer CircuitPython duty setting, from 0 to 65,535
    u = 16,384API maximum = 65,535
  2. 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
  3. Substitute and calculate.
    p
    percentage on a 0–100 scale (%)
    p ≈ 16,384 ÷ 65,535 × 100≈ 25.0004%
  4. 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 ÷ REFDIVfVCO = fPLLref × FBDIVfout = fVCO ÷ (POSTDIV1 × POSTDIV2)
  1. 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.

  2. Reference frequency:

    fPLLref
    frequency at the PLL reference input (Hz)
    fPLLref = 12 ÷ 1= 12 MHz
  3. Multiply feedback:

    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    fVCO = 12 × 125= 1500 MHz
  4. Check the VCO: 750 ≤ 1500 ≤ 1600 MHz, so this value is within the permitted range.
  5. Combined post-divider = 6 ×

    2 = 12

    . Output

    fout
    PLL output frequency (Hz)
    fout = 1500 ÷ 12= 125 MHz
  6. 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
  1. Identify values and convert units.
    REFDIV
    PLL reference divider (dimensionless)
    fXOSC
    external crystal frequency (Hz)
    fXOSC = 12 MHzREFDIV = 2
  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
  3. Substitute and calculate.
    fPLLref
    frequency at the PLL reference input (Hz)
    fPLLref = 12 ÷ 2= 6 MHz6 ≥ 5
  4. 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
  1. Identify values and convert units.
    fPLLref
    frequency at the PLL reference input (Hz)
    FBDIV
    PLL feedback multiplier (dimensionless)
    fPLLref = 12 MHzFBDIV = 64
  2. 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
  3. Substitute and calculate.
    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    fVCO = 12 × 64= 768 MHz750 ≤ 768 ≤ 1600
  4. 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
  1. Identify values and convert units.
    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    fVCO = 768 MHzcombined division = 4 × 4= 16
  2. 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)
  3. Substitute and calculate.
    fout
    PLL output frequency (Hz)
    fout = 768 ÷ 16= 48 MHz
  4. 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
  1. 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 MHzfPLLref = 12 MHzPOSTDIV1 × POSTDIV2 = 10
  2. 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
  3. Substitute and calculate.
    fVCO
    PLL voltage-controlled oscillator frequency (Hz)
    FBDIV
    PLL feedback multiplier (dimensionless)
    FBDIV = 120 × 10 ÷ 12= 100fVCO = 12 × 100= 1200 MHz
  4. 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 = 2nkmax = 2n − 1code ≈ round(Vin ÷ Vref × kmax)step ≈ Vref ÷ L
  1. 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
  2. Count L: 2^

    12 = 4096

    . Maximum raw

    code
    raw ADC code
    code = 4096 − 1= 4095
  3. Input fraction: V_in ÷

    Vref
    reference voltage (V)
    Vref = 1.65 ÷ 3.3= 0.5
  4. Endpoint-scale estimate:

    round
    round to the nearest integer
    code
    raw ADC code
    code ≈ round(0.5 × 4095)= round(2047.5)= 2048
  5. 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.

  6. 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.
  7. 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 ÷ fADCfmax = 1 ÷ tconvpacingcycles = fADC ÷ fsampleDIV.INT = pacingcycles − 1
  1. Given

    fADC
    ADC clock frequency (Hz)
    fADC = 48 MHz= 48,000,000 Hz

    and 96 clock cycles per conversion.

  2. Conversion time = 96 ÷

    s
    shaft speed (revolutions/minute, rpm)
    48,000,000 = 0.000002 s= 2

    μs.

  3. Maximum conversion rate in this model = 1 ÷

    s
    shaft speed (revolutions/minute, rpm)
    0.000002 = 500,000 samples/s= 500

    ksample/s.

  4. 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
  5. 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
  6. 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
  1. Identify values and convert units.
    Vref
    reference voltage (V)
    Vin
    input voltage (V)
    code
    raw ADC code
    raw
    raw ADC code
    Vin = 0.66 VVref = 3.3 Vmaximum raw code = 4095
  2. 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))
  3. Substitute and calculate.
    round
    round to the nearest integer
    raw
    raw ADC code
    raw ≈ round(0.66 ÷ 3.3 × 4095)= round(819)= 819
  4. 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
  1. Identify values and convert units.
    referencevoltage
    ADC reference voltage (V)
    value
    CircuitPython ADC API reading
    value = 49,152referencevoltage = 3.3 V
  2. Write the equation.
    referencevoltage
    ADC reference voltage (V)
    value
    CircuitPython ADC API reading
    V
    voltage (V)
    V ≈ value ÷ 65,535 × referencevoltage
  3. Substitute and calculate.
    V
    voltage (V)
    V ≈ 49,152 ÷ 65,535 × 3.3≈ 2.47504 V
  4. 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
  1. 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 = 12212 = 4096 LVref = 3.3 V
  2. Write the equation.
    Vref
    reference voltage (V)
    ΔV
    ideal ADC voltage-bin width (V)
    n
    counter or address width (bits)
    ΔV ≈ Vref ÷ 2n
  3. Substitute and calculate.
    ΔV
    ideal ADC voltage-bin width (V)
    ΔV ≈ 3.3 ÷ 4096= 0.000805664 V×1000 ≈ 0.805664 mV
  4. 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
  1. Identify values and convert units.
    fsample
    requested ADC sampling rate (samples/s)
    fADC
    ADC clock frequency (Hz)
    fADC = 48,000,000 Hzfsample = 2000 samples/s
  2. 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
  3. 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,000DIV.INT = 24,000 − 1= 23,999
  4. State the answer and check its meaning.

    DIV.INT = 23,999. The 24,000-cycle interval is longer than the 96-cycle conversion.

Interactive calculation bench

Change the values to see the relationship. These are teaching models; register-level PWM uses a realizable divider and counter setting.

250 ms = 250,000 μs ticksTOP and PWM frequency appear here.40% → 26214 of CircuitPython's 65535 maximum.Approximate 12-bit hardware code and scaled CircuitPython reading appear here.
Show step-by-step working for the current bench inputs

These substitutions update when you change the inputs. Integer choices are teaching examples; pwmio can choose a different realizable pair. The API-scale ADC estimate is not an exact prediction of the port’s hardware scaling.

Timer interval

ts
time interval in seconds
ticks = ts × 106
  1. Convert milliseconds to seconds.
  2. Multiply seconds by one million ticks per second.

PWM frequency and TOP

frequest
requested frequency (Hz)
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)
C
counter counts per PWM period
C = fsys ÷ (D × frequest)TOP = round(C) − 1
  1. Convert the system clock to Hz.
  2. Apply the divider to obtain the counter rate.
  3. Divide by the requested frequency to obtain ideal counts.
  4. Choose integer counts, then subtract one for TOP.
  5. Recalculate frequency using the chosen integer setting.

CircuitPython duty value

round
round to the nearest integer
p
percentage on a 0–100 scale (%)
u
integer CircuitPython duty setting, from 0 to 65,535
u ≈ round(p ÷ 100 × 65,535)
  1. Convert percentage to a fraction.
  2. Multiply by the 16-bit API maximum.
  3. Round to an integer API value.

ADC endpoint-scale estimates at 3.3 V

round
round to the nearest integer
Vin
input voltage (V)
raw
raw ADC code
r
CircuitPython ADC reading on the 0–65,535 API scale
r = Vin ÷ 3.3raw ≈ round(r × 4095)API estimate ≈ round(r × 65,535)
  1. Find the input fraction of the reference voltage.
  2. Scale to the raw 12-bit maximum and round.
  3. Separately estimate the 16-bit API scale and round.

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
  1. Given t = 1.25 s and 1 μs timer ticks.
  2. 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
  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
  2. C
    counter counts per PWM period
    C = 125,000,000 ÷ (2 × 10,000)= 6250

    .

    TOP
    PWM counter upper limit (count)
    TOP = 6250 − 1= 6249
  3. 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
  1. Given duty = 25% and period

    T
    period of one cycle (s unless another time unit is stated)
    T = 20 ms
  2. Convert percent: 25 ÷

    100 = 0.25

    . Substitute

    TON
    HIGH time within one period (same time unit as T)
    TON = 0.25 × 20 ms= 5 ms
  3. 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))
  1. Given

    Vin
    input voltage (V)
    Vin = 0.825 V

    ,

    Vref
    reference voltage (V)
    Vref = 3.3 V

    and 12-bit raw hardware code.

  2. Maximum

    code
    raw ADC code
    code = 212 − 1= 4095

    . Input fraction = 0.825 ÷

    3.3 = 0.25
  3. Unrounded estimate = 0.25 ×

    4095 = 1023.75

    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

ResourceWhat advances itPurpose
System timerOne-microsecond timebase.Measure elapsed time and schedule alarm comparisons.
Event counter, conceptAn accepted external event or edge.Count presses, revolutions or pulses; the acquisition method limits the observable rate.
PWM sliceSystem clock divided by a selected divider in normal time-based operation.Generate repeating output edges without toggling each edge in Python.
WatchdogA 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
  1. Given r_low-word width

    n
    counter or address width (bits)
    n = 32

    and one timer tick = 1 μs.

  2. Number of states = 2^

    32 = 4,294,967,296

    . Multiply by 1 μs per state:

    Twrap
    counter repeat interval (s)
    Twrap = 4,294,967,296

    μs.

  3. Convert to seconds: 4,294,967,296 ÷ 1,000,000 = 4294.967296 s.
  4. 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
  1. 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

    ticks = 0x40
  2. Add before applying the width limit: 4,294,967,280 +

    64 = 4,294,967,344= 0x100000030
  3. Reduce modulo 2^32: 4,294,967,344 −

    4,294,967,296 = 48= 0x00000030
  4. 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.
  5. 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
  1. Identify values and convert units.
    Ttick
    duration of one timer tick (s)
    n
    counter or address width (bits)
    n = 16Ttick = 1 μs
  2. Write the equation.
    Ttick
    duration of one timer tick (s)
    Twrap
    counter repeat interval (s)
    n
    counter or address width (bits)
    Twrap = 2n × Ttick
  3. Substitute and calculate.
    Twrap
    counter repeat interval (s)
    Twrap = 65,536 × 1 μs= 65,536 μs= 65.536 ms
  4. 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
  1. Identify values and convert units.
    Anow
    current timer count
    delay
    requested delay in the stated time/count unit
    Anow = 4,294,967,292delay = 12
  2. 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
  3. Substitute and calculate.
    Atarget
    target timer count
    sum
    intermediate timer-count sum
    sum = 4,294,967,304subtract 4,294,967,296 → Atarget = 8= 0x00000008
  4. 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
  1. Identify values and convert units.
    start
    initial timer count
    end
    final timer count
    start = 4,294,967,288end = 24tick = 1 μs
  2. 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
  3. Substitute and calculate.
    elapsedticks
    elapsed timer ticks
    mod
    integer remainder after division
    elapsedticks = (24 − 4,294,967,288) mod 4,294,967,296= 32
  4. 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
  1. 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
  2. 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
  3. Substitute and calculate.
    223 = 8,388,608
  4. 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 − 1Ttick = D ÷ fsys
  1. 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
  2. C
    counter counts per PWM period
    C = 125,000,000 ÷ (1 × 1000)= 125,000

    ;

    TOP
    PWM counter upper limit (count)
    TOP = 124,999
  3. Reject this choice: TOP 124,999 exceeds the 16-bit maximum 65,535.
  4. 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.

  5. One divided tick = 2 ÷

    s
    shaft speed (revolutions/minute, rpm)
    125,000,000 = 0.000000016 s= 16 ns
  6. Period = 62,500 × 16

    ns = 1,000,000 ns= 1 ms

    . 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
  1. 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
  2. Cideal
    ideal real-valued period count
    Cideal = 125,000,000 ÷ 3000= 41,666.666

    … counts, which is not an integer.

  3. 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.

  4. Recalculate

    factual
    realized frequency (Hz)
    factual = 125,000,000 ÷ 41,667≈ 2999.976 Hz
  5. Error = 2999.976 −

    3000 ≈ −0.024 Hz

    , 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
  1. Identify values and convert units.
    fsys
    system-clock frequency (Hz)
    f
    frequency (Hz, cycles per second)
    fsys = 125,000,000 Hzf = 500 Hz
  2. 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
  3. Substitute and calculate.
    Dmin
    minimum divider before hardware-grid rounding
    ceil
    round upward to an integer
    Dmin = 3.814697265625ceil(16 × Dmin) ÷ 16 = 62 ÷ 16= 3.875
  4. 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
  1. 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 HzD = 1frequest = 7000 Hz
  2. 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
  3. Substitute and calculate.
    Cchosen
    selected integer period count
    Cideal
    ideal real-valued period count
    TOP
    PWM counter upper limit (count)
    Cideal ≈ 17,857.142857Cchosen = 17,857TOP = 17,856
  4. 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
  1. Identify values and convert units.
    frequest
    requested frequency (Hz)
    factual
    realized frequency (Hz)
    factual = 7000.056 Hzfrequest = 7000 Hz
  2. Write the equation.
    frequest
    requested frequency (Hz)
    factual
    realized frequency (Hz)
    Δf
    signed frequency difference (Hz)
    Δf = factual − frequest
  3. Substitute and calculate.
    Δf
    signed frequency difference (Hz)
    Δf = 7000.056 − 7000= +0.056 Hz
  4. 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
  1. Identify values and convert units.
    frequest
    requested frequency (Hz)
    factual
    realized frequency (Hz)
    factual = 2999.976 Hzfrequest = 3000 Hz
  2. Write the equation.
    errorpercent
    relative frequency error (%)
    frequest
    requested frequency (Hz)
    factual
    realized frequency (Hz)
    errorpercent = (factual − frequest) ÷ frequest × 100
  3. Substitute and calculate.
    errorpercent
    relative frequency error (%)
    errorpercent = (−0.024 ÷ 3000) × 100= −0.0008%
  4. 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 ÷ fp = TON ÷ T × 100u ≈ round(TON ÷ T × 65,535)
  1. 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
  2. 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
  3. 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
  4. 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
  5. 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
  1. Identify values and convert units.
    f
    frequency (Hz, cycles per second)
    f = 50 Hz
  2. Write the equation.
    T
    period of one cycle (s unless another time unit is stated)
    f
    frequency (Hz, cycles per second)
    T = 1 ÷ f
  3. 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
  4. 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
  1. 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 msT = 20 ms
  2. 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)
  3. Substitute and calculate.
    round
    round to the nearest integer
    ratio
    dimensionless pulse-width fraction
    ratio = 0.060.06 × 65,535 = 3932.1round → 3932
  4. 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
  1. 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 = 4915T = 20 ms
  2. 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
  3. Substitute and calculate.
    TON
    HIGH time within one period (same time unit as T)
    TON ≈ 4915 ÷ 65,535 × 20≈ 1.49996 ms
  4. 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
  1. 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 msTON = 1.8 ms
  2. 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
  3. Substitute and calculate.
    TOFF
    LOW time within one period (same time unit as T)
    TOFF = 20 − 1.8= 18.2 ms
  4. 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.

Time since model start0 ms
Timeout remaining2000 ms
Feeds completed0
Application on RP2040Hardware watchdog · runs independentlyInitialize outputs and watchdogRESET · timeout = 2.0 sRead sensorValid reading?Decide and update outputHeater ON or OFFOutput checks pass?Feed after useful progressw.feed()No feed · handle/report the faultYesNoYesNoTimeout configured by firmwareIndependent countdownFeed reloads the timeoutTimeout expired?RP2040 reset pathFirmware starts againYesNoFeed event → reload

Requested output:

This manual simulation uses a 2 s timeout. A healthy loop models 120 ms sensor work, 80 ms output work and 200 ms waiting; validation/feed execution time is omitted. During a fault, advancing the simulation advances the independent countdown. A reset restarts firmware; it does not erase flash or guarantee the external fault has disappeared. No physical board or heater is controlled.

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 + tdelayM = Ttimeout − Tloop
  1. 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
  2. Add the work:

    Tloop
    loop duration
    s
    shaft speed (revolutions/minute, rpm)
    Tloop = 0.12 + 0.08 + 0.20= 0.40 s= 400 ms
  3. For the illustrative

    Ttimeout
    watchdog timeout
    Ttimeout = 2.0 s

    ,

    M
    available time margin
    M = 2.0 − 0.40= 1.60 s
  4. Ratio = 2.0 ÷

    0.40 = 5

    nominal loop durations. This does not prove the worst-case workload will fit; measure legitimate blocking/communication delays and leave suitable M.

  5. 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.NONE

In 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
  1. Identify values and convert units.
    tdisplay
    display update duration (s)
    tsensor
    sensor operation duration (s)
    Tsleep
    sleep duration
    tsensor = 0.15 stdisplay = 0.05 sTsleep = 0.25 s
  2. Write the equation.
    tdisplay
    display update duration (s)
    tsensor
    sensor operation duration (s)
    Tsleep
    sleep duration
    Tloop
    loop duration
    Tloop = tsensor + tdisplay + Tsleep
  3. Substitute and calculate.
    Tloop
    loop duration
    Tloop = 0.15 + 0.05 + 0.25= 0.45 s
  4. 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
  1. Identify values and convert units.
    Ttimeout
    watchdog timeout
    Tloop
    loop duration
    Ttimeout = 1.5 sTloop = 0.45 s
  2. Write the equation.
    Ttimeout
    watchdog timeout
    Tloop
    loop duration
    M
    available time margin
    M = Ttimeout − Tloop
  3. Substitute and calculate.
    M
    available time margin
    M = 1.5 − 0.45= 1.05 s
  4. 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
  1. Identify values and convert units.
    t_worst_valid
    measured worst-case valid loop duration (s)
    M
    available time margin
    t_worst_valid = 1.1 sM = 0.4 s
  2. 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
  3. Substitute and calculate.
    Ttimeout
    watchdog timeout
    Ttimeout = 1.1 + 0.4= 1.5 s
  4. 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
  1. Identify values and convert units.
    Ttimeout
    watchdog timeout
    Tsleep
    sleep duration
    tother
    time spent on other valid operations (s)
    Ttimeout = 2.0 stother = 0.12 sTsleep = 0.20 s
  2. Write the equation.

    t_block < timeout − t_other − t_sleep

  3. 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
  4. 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 × 106ftask = 1 ÷ periods
  1. Given A_target period = 200 ms. Convert to seconds: 200 ÷

    1000 = 0.200 s
  2. Convert to nanoseconds:

    periodns
    schedule period in nanoseconds
    periodns = 200 × 1,000,000= 200,000,000 ns

    , matching the code below.

  3. Nominal task rate = 1 ÷

    0.200 = 5

    executions/s.

  4. 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
  1. Identify values and convert units.
    periodms
    schedule period in milliseconds
    periodms = 1251 ms = 1,000,000 ns
  2. Write the equation.
    periodns
    schedule period in nanoseconds
    periodms
    schedule period in milliseconds
    periodns = periodms × 106
  3. Substitute and calculate.
    periodns
    schedule period in nanoseconds
    periodns = 125 × 1,000,000= 125,000,000 ns
  4. 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
  1. Identify values and convert units.
    periods
    schedule period in seconds
    periods = 0.125 s
  2. Write the equation.
    periods
    schedule period in seconds
    ftask
    task executions per second
    ftask = 1 ÷ periods
  3. Substitute and calculate.
    ftask
    task executions per second
    ftask = 1 ÷ 0.125= 8 executions/s
  4. 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
  1. Identify values and convert units.
    previousdue
    previous scheduled timestamp (ns)
    periodns
    schedule period in nanoseconds
    previousdue = 1,000,000,000 nsperiodns = 125,000,000 ns
  2. Write the equation.
    previousdue
    previous scheduled timestamp (ns)
    periodns
    schedule period in nanoseconds
    nextdue
    next scheduled timestamp (ns)
    nextdue = previousdue + periodns
  3. Substitute and calculate.
    nextdue
    next scheduled timestamp (ns)
    nextdue = 1,000,000,000 + 125,000,000= 1,125,000,000 ns
  4. 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
  1. Identify values and convert units.
    deadline
    scheduled timestamp (ns)
    now
    current timestamp (ns)
    now = 1,130,000,000 nsdeadline = 1,125,000,000 ns
  2. 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)
  3. Substitute and calculate.
    latenessns
    lateness in nanoseconds
    latenessms
    lateness in milliseconds
    latenessns = 5,000,000 nslatenessms = 5,000,000 ÷ 1,000,000= 5
  4. State the answer and check its meaning.

    The task is 5 ms late. This measures software lateness, not a hardware PWM edge error.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. The RP2040 system timer increments once every…

Bloom: Remember

2. Convert 250 ms into timer ticks at 1 MHz.

Bloom: Apply

3. A PWM uses clk_sys = 125 MHz, divider = 1 and TOP = 6249. Normal-mode frequency?

Bloom: Apply

4. A PWM has TOP = 999 and compare level = 250. Approximate duty cycle?

Bloom: Apply

5. At 50 Hz, what is the PWM period?

Bloom: Apply

6. Why can CircuitPython’s reported PWM frequency differ slightly from the requested frequency?

Bloom: Analyse

Not checked yet

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 × ftickNtick = 0.250 s × 1,000,000 ticks/sNtick = 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 = 6250TOP = C − 1TOP = 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 − TloopM = 1.5 s − 0.45 sM = 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

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 & bootROM / flashCircuitPythonruntime + librariesInitializepins / objectsReadsensor / buttonProcessscale / decideUpdate outputdisplay / 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+

16 = 20 ms

; 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 actionHardware/software interpretation
Read pot.valueADC samples GP28; the driver returns a scaled integer.
Calculate level_percentThe 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 msPause 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 symptomQuestions to investigate
No application output after resetDid firmware boot, did code.py load, and did initialization raise an exception?
A reading stays fixedIs the correct pin/interface selected? Is the signal changing? Does a new conversion complete?
The buffer changes but LEDs do notWas show called? Is the correct signal pin selected? Are power and ground correct?
A motor command is present but the shaft is stoppedCheck the driver, motor supply, terminals, load and physical connections.
Repeated resetsDistinguish watchdog expiry, power problems and explicit reset requests; inspect the preceding workload.
Timing is slower than predictedInclude 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.

Six-question self-check

Assessment alignment: CLO1 · Bloom levels include Remember, Understand, Apply, and Analyse. Calculation items show the working expected in a test.

1. Which order best describes a simple embedded control cycle?

Bloom: Understand

2. What occurs before a CircuitPython user program can control an EDU PICO peripheral?

Bloom: Understand

3. A sensor is sampled every 20 ms. Ideal sample rate?

Bloom: Apply

4. A loop takes 4 ms to process and then calls sleep(0.016). Approximate loop period and rate?

Bloom: Apply

5. Why can `time.sleep(0.02)` fail to create an exact 20 ms output edge interval?

Bloom: Analyse

6. A watchdog is most useful when a system must…

Bloom: Understand

Not checked yet

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 + TsleepTloop = 4 ms + 16 msTloop = 20 msfs = 1 ÷ Tloopfs = 1 ÷ 0.020 sfs = 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 msTloop = 24 msfs = 1 ÷ 0.024 sfs ≈ 41.67 samples/s

Interpretation: Keeping the sleep unchanged does not keep the whole loop period unchanged.

Hardware Module 01: Push buttons

Learning goalRead 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 signalEDU PICO connectionCircuitPython pinMeaning
Button A outputOnboard button AGP0Digital input with internal pull-up
Button B outputOnboard button BGP1Digital input with internal pull-up
OLED I2COnboard I2C busSDA GP4, SCL GP5Displays 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 tutorialRun 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 goalRead 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
SDAI2C Grove/onboard I2CGP4Bidirectional measurement data
SCLI2C Grove/onboard I2CGP5I2C clock
VCC/GNDI2C port power3V3/GNDSensor 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 tutorialRun 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 goalMeasure 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
SDAI2C Grove/onboard I2CGP48-bit proximity value
SCLI2C Grove/onboard I2CGP5I2C clock
VCC/GNDI2C port power3V3/GNDSensor 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 tutorialRun 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 goalCalculate 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
SDAI2C Grove/onboard I2CGP4RGBC data, lux, and colour temperature
SCLI2C Grove/onboard I2CGP5I2C clock
VCC/GNDI2C port power3V3/GNDSensor 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 tutorialRun 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 goalRecognise 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
SDAI2C Grove/onboard I2CGP4Numeric gesture code
SCLI2C Grove/onboard I2CGP5I2C clock
VCC/GNDI2C port power3V3/GNDSensor 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 tutorialRun 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 goalRead 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
SDAI2C Grove/onboard I2CGP4Red, green, blue, and clear channels
SCLI2C Grove/onboard I2CGP5I2C clock
VCC/GNDI2C port power3V3/GNDSensor 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 tutorialRun 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 goalCapture 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 signalEDU PICO connectionCircuitPython pinSensor output
DATAOnboard PDM microphoneGP2Pulse-density audio samples
CLOCKOnboard PDM microphoneGP3Sampling clock generated by Pico
OLED I2COnboard I2C busSDA GP4, SCL GP5Displays 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 tutorialRun 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 goalConvert 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 signalEDU PICO Grove/board portCircuitPython pinSensor output
Wiper/SIGAnalogue input/onboard potentiometerGP28 / ADC20–3.3 V analogue level
VCCPort power3V3Top of resistive track
GNDPort groundGNDVoltage 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 tutorialRun 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 goalMount, 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 signalEDU PICO port/socketCircuitPython pinDirection
MISOOnboard microSD socketGP16Card → EDU PICO data
CSOnboard microSD socketGP17EDU PICO → card select
SCKOnboard microSD socketGP18EDU PICO → card clock
MOSIOnboard microSD socketGP19EDU 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 tutorialRun 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 goalRead 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 signalEDU PICO connectionCircuitPython pinMeaning
LOG switch outputOnboard flash-log switchGP15Low = logging selected; high = not selected
OLED I2COnboard I2C busSDA GP4, SCL GP5Shows 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 tutorialRun 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 goalDecode 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 hardwareThe 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.

M11: Capacitive keypad

Interfacing connection

Keypad signalEDU PICO Grove/UART portCircuitPython pinDirection
Keypad RXUART receive terminal on keypadGP20 TXEDU PICO → keypad
Keypad TXUART transmit terminal on keypadGP21 RXKeypad output → EDU PICO
VCC/GNDUART Grove port power3V3/GNDModule power/common reference
Cross the UART data wiresKeypad 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 tutorialRun 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 goalControl 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 signalEDU PICO connectionCircuitPython pinPurpose
DINOnboard RGB LED chainGP14Serial colour data for five LEDs
Power/GroundOnboard supplyBoard-managedPowers the LED chain
OLED I2COnboard I2C busSDA GP4, SCL GP5Shows 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 tutorialRun 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 goalPlay 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 signalEDU PICO connectionCircuitPython pinPurpose
Buzzer driveOnboard passive buzzerGP21PWM frequency produces a musical tone
Audio outputOnboard audio jack/pathGP20Alternative audio signal path
OLED I2COnboard I2C busSDA GP4, SCL GP5Displays 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 tutorialRun 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 goalControl 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 signalEDU PICO Grove/board portCircuitPython pinDirection/purpose
Servo signalServo portGP6EDU PICO → servo PWM command
Servo V+/GNDServo power portExternal/board supply and GNDMotor power; grounds must be common
Potentiometer SIGOnboard analogue inputGP28 / ADC2User position command → EDU PICO
OLED I2COnboard I2C busSDA GP4, SCL GP5Displays 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 tutorialRun 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 goalRamp 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 signalEDU PICO terminal/driverCircuitPython pinPurpose
Motor 1 input A/BOnboard motor driver channel 1GP10 / GP11Unused in this standalone program
Motor 2 input A/BOnboard motor driver channel 2GP12 / GP13Direction and PWM speed
Motor outputsM1/M2 screw terminalsDriver outputsDriver → motor power
Motor supply/GNDMotor power inputExternal supply/common GNDSupplies 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 tutorialRun 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 goalToggle 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 signalEDU PICO connectionCircuitPython pinPurpose
Relay controlOnboard USB relay circuitGP22Digital output switches USB power
USB loadSwitched USB outputRelay power pathReceives power when enabled
OLED I2COnboard I2C busSDA GP4, SCL GP5Displays 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 tutorialRun 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 goalRotate 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 hardwareThe 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.

M17: Stepper motor

Interfacing connection

ULN2003 signalEDU PICO connectionCircuitPython pinPurpose
IN1Digital outputGP26Stepper coil sequence channel 1
IN2Digital outputGP27Stepper coil sequence channel 2
IN3Digital outputGP8Stepper coil sequence channel 3
IN4Digital outputGP7Stepper coil sequence channel 4
VCC/GNDDriver motor supplyExternal supply/common GNDSupplies 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 tutorialRun 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 goalCount 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 hardwareThe 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.

M18: Four-digit display

Interfacing connection

Display signalEDU PICO Grove/board portCircuitPython pinPurpose
SDAI2C Grove portGP4EDU PICO → TM1650 command/data
SCLI2C Grove portGP5I2C clock
VCC/GNDI2C Grove port power3V3/GNDDisplay 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 tutorialRun 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

  1. Create a LAB1 folder on your computer. Save guided practice separately, then use the exact assignment filenames listed below.
  2. 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.
  3. 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 / settingPurpose
SDA → GP4; SCL → GP5I²C data and clock; busio.I2C takes SCL first, then SDA.
3V3 / GNDUse 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 / settingPurpose
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

  1. 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.
  2. Keep all text within the screen without overlap. State the x/y coordinates and size chosen for each line.
  3. 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 / settingPurpose
brightness=0.1Use 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

  1. 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.
  2. Choose and document the RGB tuple for each colour. Ensure pixels 1–4 are off during the red state.
  3. 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 / settingPurpose
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

  1. Count down from 0099 to 0001 continuously, with a 0.1-second interval for each displayed value.
  2. Keep four-digit zero padding. After 0001, restart at 0099 without displaying 0000.
  3. 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 / settingPurpose
variable_frequency=TrueAllow the PWM frequency to change between tones.
buzzer.frequencySet pitch in hertz; frequency is not note duration.
duty_cycle=32768Approximately 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

  1. Play a notification: 523 Hz for 0.2 seconds, silence for 0.2 seconds, then 784 Hz for 0.2 seconds.
  2. 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.
  3. 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

SymptomCheck / action
ValueError: incompatible .mpy fileReplace incompatible libraries with the firmware-matching bundle; replace complete library folders, then restart and rerun the import check.
ImportErrorCheck the library filename and folder. TM1650Display.py belongs in edu_pico_lib; Adafruit libraries belong in lib.
Blank OLED / clipped textCheck 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 useStop the previous program and run cleanup. Reset before changing parts if resources remain allocated.
RGB colours do not updateCheck GP14, pixel indexes and pixels.show() when auto_write=False.
No buzzer soundCheck GP21, the Method 1 selector and a nonzero duty cycle during the tone.

5. Assignment submission checklist

PartDeviceRequired filename
AOLEDLAB1_partA.py
BRGB LEDLAB1_partB.py
CSeven-segment displayLAB1_partC.py
DBuzzerLAB1_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

  1. 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

  1. 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

  1. 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

SymptomCheck / action
Servo does not move to the requested angleCheck GP6, servo-port connection, common ground, 50 Hz frequency, pulse calculation, and mechanical range.
Stepper vibrates or turns in the wrong directionCheck 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 reverseCheck the HX1515H driver, GP10/GP11 channel, motor supply and throttle value. Set throttle to zero before changing direction.
ImportError for adafruit_motorInstall 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

  1. 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

  1. 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

SymptomCheck / action
Button state appears reversedRemember that the buttons are active-low. With Pull.UP, True means released and False means pressed.
Button action repeats unexpectedlyCheck that the program detects a press edge and updates the previous-state variable on every loop.
No keypad bytes are receivedCheck crossed TX/RX wiring, GP20/GP21, 9600 baud, selector configuration, power, and ground.
Keypad displays the wrong keyPrint 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

  1. 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

  1. 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

SymptomCheck / action
AHT20 import failsInstall the matching adafruit_ahtx0 library and required dependencies, then restart the board.
AHT20 is not detected or readings failCheck shared I²C SDA GP4 / SCL GP5, sensor power, and that the OLED and AHT20 use the same bus object.
Potentiometer value does not changeConfirm the potentiometer input is GP28 / ADC2 and that the AnalogIn object is read inside the loop.
Calculated voltage or percentage seems incorrectUse 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