Labs / MicroPython tutorials

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Author: Li Zisheng · Source: FreakStudio open documentation, v1.2.0 · License: CC BY 4.0

Contents

1. Hardware Explanation

1.1 Basic Concept and Structure of MCU

Before we start learning about the GPIO of the Raspberry Pi Pico, let's first explain several core "hardware basic concepts" in simple terms. The Raspberry Pi Pico is an MCU development board, and you can understand an MCU (Microcontroller Unit) as an ultra-miniature dedicated computer — it cannot handle as many tasks as our desktop/laptop computers, but it is specifically responsible for controlling a certain electronic device (such as a smart light, a remote control, or a small toy you make with the Raspberry Pi Pico): for example, when you use the Pico to control an LED to turn on and off, this core component that "issues commands and manages execution" is the MCU.

MCU (Microcontroller) is widely used to control all types of electronic devices, and an MCU consists of a CPU (Central Processing Unit), a memory, and additional circuits that implement various peripheral support functions:

Peripherals, memory and the CPU are connected via a bus, which acts as the "expressway" inside an MCU:

Diagram: 04 GPIO General Purpose Input/Output —— Document Tutorial Draft

All data and instructions must be transmitted via the bus: for example, if the CPU wants the GPIO to turn on an LED, it has to send the "turn on LED command" to the GPIO peripheral through the bus; the sensor data read by the peripheral also has to be transmitted to the CPU via the bus.

The bus structure of the Raspberry Pi Pico is as follows:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
Dual-core microcontroller system architecture

It can be seen that Core 0 and Core 1 are connected to the DMA unit, SRAM memory unit, APB bus bridge and some high-speed peripherals (such as FLASH XIP, PIO, USB, etc.) through the AHB high-speed bus matrix structure. The APB bus bridge is connected to the APB bus, which mounts other low-speed peripherals, such as UART, SPI, IIC, ADC, PWM, timers, watchdog, RTC real-time clock, etc.

When we want to use a certain peripheral to implement a specific function, such as controlling a GPIO to light up an LED, we are essentially operating "registers": they are "special dedicated storage circuits" inside the CPU or in peripheral circuits like GPIO and ADC, and are ultra-high-speed temporary storage units — they are far faster than conventional memory, but due to the precious internal space of the chip, only a small number of such units are available (unlike memory which can store large amounts of data);Each peripheral (such as GPIO or a timer) corresponds to several "dedicated registers"; when the CPU wants to control a specific peripheral, it simply accesses the corresponding registers of that peripheral directly.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Registers can be divided into the following two types:

CPU controls peripheral devices by reading from and writing to the dedicated registers corresponding to the peripherals to issue commands or read data:

Why should MicroPython developers also understand registers? (Core Key Points)

You might ask: "I write code entirely in MicroPython by calling library functions (for example machine.Pin (25, machine.Pin.OUT). on ()), so why do I still need to understand registers? "

This is because the library functions of MicroPython essentially encapsulate register read and write operations into simple commands, but in many scenarios, you still need to directly work with registers — especially for the advanced features of the Raspberry Pi Pico:

  • Scenario 1: Advanced operations not covered by the MicroPython library such as DMA operations, advanced PIO (Programmable I/O) configuration, and precise clock control: the basic MicroPython library does not provide a ready-made simple function, so in this case you have to use machine.mem32 (the register read-write interface of MicroPython) to directly read and write registers to implement the function.To give a straightforward example: if you need to configure DMA transfer, you first have to find the address of the DMA control register, then use mem32[address] = configuration value to set the parameters, and use mem32[address]to read the transfer status.
  • Scenario 2: Understand both the what and the why, and avoid "Black box programming": Understanding registers allows you to see exactly what operations the pin.on () you wrote actually triggers in the underlying hardware (essentially writing a 1 to the GPIO output register). This helps you grasp the correspondence between code and hardware, rather than just mindlessly copying code to call a function.
  • Scenario 3: Troubleshooting and Custom Functions: When your MicroPython program encounters hardware-related bugs (such as abnormal GPIO output or failed DMA transmission), understanding registers allows you to quickly locate the problem (for example, checking whether the configuration values of registers are correct); if you want to implement custom functions that are not available in library functions (such as a special GPIO interrupt trigger mode), you also need to make adjustments via registers.Simply put, registers are the "hardware operation shortcuts" in a microcontroller — through them, we can quickly access and manipulate low-level hardware resources such as IO ports, DMA, and timers, and they are also the necessary path for MicroPython to operate the advanced functions of the Pico.

1.2 Basic Structure and Concepts of GPIO

GPIO (General Purpose Input/Output) ports are used to process incoming and outgoing digital signals:

GPIO is referred to as a "general-purpose" input/output port because each of its pins can be freely configured as either an input or an output. In early microcontroller units (MCUs), by contrast, each port was dedicated exclusively to either input or output functionality.

The logical structure of an example GPIO in the Raspberry Pi Pico is shown in the following figure:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO pin control logic architecture

The figure above shows the control logic architecture diagram of GPIO pins:

The "controller" of GPIO is selected via the Muxing (multiplexer), which falls into two scenarios:

For the GPIO of the Raspberry Pi Pico, the control over GPIO is actually realized by writing to and reading from different bits of the GPIOx_STATUS register and the GPIOx_CTRL register.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO status register bit field description

GPIOx_STATUS register is a status panel that can only be read but not modified (marked as RO = Read-Only), and its function is to "inform you of the current real status of GPIO ", for example:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO control register bit field description

GPIOx_CTRL register serves as the configurable control center (type: RW = read/write), and all operations you perform on GPIO such as function configuration and signal inversion are implemented by writing to this register:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO peripheral function multiplexing table

The figure above is the "list of functions that each GPIO can switch between", which corresponds to the previously mentioned "Muxing selection":

When we operate the GPIOx_CTRL register's FUNCSEL bits, we are selecting the function corresponding to column F here — for example, if you select "F5 (SIO)", the GPIO will be controlled by SIO software; if you select "F1 (SPI0 RX)", the GPIO will become the receive pin of SPI.

Each GPIO is connected to the off-chip world via a "Pads". Pads are the electrical interfaces between the on-chip logic and external circuits, which convert signal voltage levels, support higher currents, and provide protection against some electrostatic discharge (ESD) events.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO pin hardware structure

Simply put, "Pads" serve as the "intermediate interface" between GPIO and external circuits. They are responsible for converting the weak signals inside the chip into voltage/current that external circuits can accept, and also protect the chip from being damaged by static electricity.

The "electrical signals" compatible with external circuits that originate from signals inside the chip can be divided into three paths:

The electrical characteristics of "Pads" can be adjusted to meet the requirements of external circuits. The following adjustments are available:

We can use the following registers to control the Pad:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
Voltage select register bit field description

This register is only 1 bit wide and is used to select whether the GPIO uses 3.3V or 1.8V:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO general register bit field description
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
SWCLK pin control register bit field description
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
SWD pin control register bit field description

SWCLK is the clock pin of the SWD (Serial Wire Debug) interface on the Pico — the SWD is the interface used for flashing programs and debugging code on the Pico — and the SWCLK Register is a register dedicated to controlling the pad electrical characteristics of this debug pin, whose function is to ensure stable and compatible signal transmission between the SWCLK pin and the external debugger.

Earlier, we covered the function switching and electrical configuration of GPIO. Now, if a GPIO "encounters an event" — say, a key press — how can it actively "alert the CPU to handle it"? This is where GPIO external interrupts come in, which act as the GPIO's "emergency call feature".

The CPU originally executes programs in sequence. When the GPIO triggers an interrupt, the CPU pauses its current task, first handles the "emergency" from the GPIO (for example, turning on an LED when a button is pressed), and then returns to the previous program to continue execution. This enables the Pico to respond to external events in real time without constantly monitoring the GPIO.

GPIO External Interrupt

External interrupt is an internal mechanism for a microcontroller to process external events in real time. When a certain external event occurs, the interrupt system of the microcontroller will force the CPU to suspend the program being executed and turn to process the interrupt event; after the interrupt processing is completed, it returns to the interrupted program and continues execution. The GPIO of the Raspberry Pi Pico can trigger interrupts by four types of events, including rising edge trigger, falling edge trigger, high level trigger and low level trigger.

GPIO external interrupts can be configured into the following four types, and the interrupt type can be modified at any time:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
GPIO interrupt trigger modes

Simply put, GPIO will "place an emergency call" in the following 4 scenarios:

For the Raspberry Pi Pico, each of its two cores has an independent external interrupt system, which means that the GPIO can "call Core 0" as well as "call Core 1" without interfering with each other.

Taking core 0 as an example, the PROC0_INTEx registers (x: 0~3) are mainly used to enable or disable interrupts, the PROC0_INTFx registers (x: 0~3) are used to force or mask the execution of external interrupts, and the PROC0_INTSx registers (x: 0~3) are used to check the interrupt status after masking or forced execution.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
PROC0 interrupt control register group

Simply put, it means:

After a GPIO triggers an interrupt, the "call information" will be stored in the INTR register. Please note two key points:

Furthermore, there are 4 INTR registers in total, corresponding to different GPIO ranges:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
Raw interrupt registers (full series)

Here, we need to distinguish between raw interrupts and masked interrupts. In the GPIO interrupt system of the Raspberry Pi Pico, an interrupt event goes through two stages from "occurrence" to "being processed by the kernel": "raw event generation" and "event filtering/masking", which correspond to the two core concepts of raw interrupt and masked interrupt. Let's use express delivery as an analogy:

A raw interrupt (the unfiltered "raw interrupt event") refers to the original event directly generated at the hardware level when the GPIO meets the interrupt trigger conditions (such as a rising edge or a high level), which serves as the "source" of the interrupt:

Post-mask interrupt (the filtered "kernel-responsive interrupt") refers to the interrupt event that can be perceived and processed by the corresponding kernel after being filtered through configurations such as interrupt enable and interrupt masking based on the original interrupt:

Put simply, the raw interrupt is the prerequisite for the masked interrupt (if no courier comes, you can never receive the parcel); the masked interrupt is the filtered result of the raw interrupt (the courier may not necessarily reach your doorstep even if they arrive).

Once you understand the raw interrupt and the post-mask interrupt, it becomes very clear that the INTR register and the INTS register are fundamentally different — they act as the "recorders" for these two stages respectively:

DimensionINTR register (raw interrupt log)INTS register (core interrupt to-do list)
Interrupt types recordedRecords raw interrupts (all GPIO interrupt events that actually occurred)Records masked interrupts (effective interrupt events the core can perceive)
ScopeGlobal (not specific to Core0/Core1; shared by all cores)Core-specific (e.g., PROC0_INTSx belongs only to Core0)
Affected by configuration?No (recorded whenever an interrupt occurs, regardless of whether it is enabled or masked)Yes (recorded only if the interrupt is enabled and not masked)
OperationEdge-triggered bits can be cleared by writing 1 (clears processed raw log entries); level-triggered bits are read-onlyRead-only (can only view the core's pending interrupt status; cannot modify)
AnalogyAll parcel records at the neighborhood parcel station (whether or not the parcels have been picked up)The list of parcels waiting for pickup at your door (only parcels that can be delivered to your home are listed here)

As a practical example, when GPIO0 triggers a rising-edge interrupt:

  1. Original interrupt occurs: the bit corresponding to GPIO0 in the INTR0 register will be set to 1 (recording that "the courier has arrived at the residential complex");
  2. If you have enabled the rising-edge interrupt for GPIO0 via PROC0_INTE0 and it is not masked by PROC0_INTF0:
    • Interrupt after masking generation: The bit corresponding to GPIO0 in the PROC0_INTSx register will be set to 1 (to record "the courier has arrived at your doorstep");
    • Core0 will sense this interrupt and suspend the current program for processing;
  3. After you handle the interrupt, write 1 to the GPIO0 bit of the INTR0 register to clear this original record (equivalent to "confirming that the express delivery has been signed for");
  4. If you have previously disabled the interrupt enable function of GPIO0:
    • The INTR0 register will still be set to 1 (the original interrupt remains);
    • The PROC0_INTSx register will not be set to 1 (no interrupt will be generated after being masked);
    • Core0 will not perceive this interrupt at all, as if it had never occurred.

1.3 Overview of GPIO on Raspberry Pi Pico

1.3.1 Introduction to IO Port Functions of Raspberry Pi Pico

Simply put, the Raspberry Pi Pico has 26 usable pins led out to the external header pins. GPIO 0 to GPIO 22 support digital signal input and output (adopting the TTL level standard: the high level is around 3.3V and the low level is around 0V), while GPIO 26 to 28 are analog signal input pins.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
Add figure caption and number

By default, GPIO 0 to 25 are bidirectional digital pins (usable as input or output) in pull-down state, with a default drive current of 4 mA; GPIO 26 to 29 can be used as analog inputs or digital IOs, with a default drive current of 4 mA.

Besides, Raspberry Pi Pico exposes the RUN pin, which can only be used as a digital signal input. By default, the RUN pin is in a pulled-up state, and if the RUN pin is pulled low, the chip will reset and restart.

1.3.2 Electrical Parameters of GPIO Ports

The following electrical parameters are the "hardware usage rules" for the Raspberry Pi Pico GPIO — which is equivalent to the "safe operation manual" for GPIO: failure to comply will either result in abnormal GPIO operation (such as erratic signal fluctuations) or directly burn out the hardware.

1.3.2.1 Maximum and minimum rated voltages
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

This set of parameters represents the physical damage threshold of the GPIO, which determines the voltage range that the GPIO can withstand:

ParameterRangeActual effect
I/O Supply Voltage
(IOVDD, IO supply voltage)
-0.5 ~ 3.63 VUpper voltage limit for powering the GPIO: for example, if you power the Pico's IO pins with 5V, exceeding 3.63V will directly burn out the GPIO.
Voltage at IO
(VPIN, IO pin voltage)
-0.5 ~ IOVDD+0.5 VMaximum voltage an IO pin can withstand: for example, when IOVDD is 3.3V, VPIN must not exceed 3.8V, otherwise the pin will be damaged by voltage breakdown.
1.3.2.2 Digital IO Parameters

When IOVDD = 3.3V:

  1. For digital inputs:
    • The high and low level range of digital input refers to the voltage interval within which GPIO can correctly identify signals, which directly affects signal reliability;
    • High level: The voltage ranges from 2 V to 3.6 V. If the input voltage is lower than 2 V (e. g., a sensor output of 1.8 V), the GPIO will misidentify a signal that should be a high level as a low level;
    • Low level: The voltage ranges from -0.3 V to 0.8 V. If the input voltage is higher than 0.8 V (for example, the voltage is 1 V after the key is released), the GPIO will misidentify the signal that should be a low level as a high level.
  2. For digital outputs:
    • The high and low levels of the digital output plus the drive current constitute the upper limit of the GPIO’s capability to drive external devices;
    • High level: The voltage ranges from 2.62 V to 3.3 V, with a maximum drive current of 12 mA. For example, it can properly drive a 5 mA LED, but will fail to "power" a 20 mA device (the device will not function, and the GPIO may even be burned out);
    • Low level: Voltage ranges from 0 to 0.5 V, with a maximum drive current of 12 mA

Also note that the total drive current of all GPIO pins should be less than 50 mA (for example, connecting 5 LEDs of 10 mA at the same time is just within the limit, while connecting 6 will cause overload and affect the power supply stability of Pico).

The resistance values of the internal pull-up and pull-down resistors range from 50k to 80k ohms, and this parameter affects the stability of the input signal. For example, when an internal pull-up resistor is used in a key circuit, a resistance within this range can keep the GPIO stably at a high level when the key is released; if the resistance is too small, it will consume extra power, while if it is too large, the anti-interference capability will become weaker.

1.3.2.3 Analog IO Parameters

The input voltage range of the ADC is from 0 to the supply voltage of the ADC_AVDD analog-to-digital converter, and the minimum internal input impedance of the ADC is 100 kΩ:

2. Software Control Method

General Purpose Input/Output (GPIO) is mainly initialized and controlled via the Pin class in the machine module. The Pin class is typically associated with physical GPIO pins that can drive output voltages and read input voltages. It provides methods to control the pin mode (such as IN, OUT) as well as to get and set digital logic levels. For analog control of pins, please refer to the ADC class.

2.1 Constructor of the machine.Pin Class

The constructor of the machine.Pin class is as follows:

class machine.Pin(id, mode=- 1, pull=- 1, *, value, drive, alt)

The parameters are defined as follows:

  • id is mandatory and can be any object. Possible value types include: int (internal Pin identifier), str (Pin name), and tuple ([port, pin] pair)
  • mode specifies the pin mode, which can be one of the following:
    • Pin.IN - The pin is configured as an input. When regarded as an output, this pin is in a high-impedance state.
      • The high-impedance state is neither a high level nor a low level; its extremely high impedance is equivalent to an open circuit. A pin in the high-impedance state exhibits uncertain voltage characteristics externally. Setting a port to the high-impedance state is equivalent to disconnecting that port from the circuit, and it will not affect other circuits.
      • High-impedance state is commonly used in bus structures.
    • Pin.OUT - The pin is configured as a (normal) output, i. e., a push-pull output.
      • The push-pull output can truly output high level and low level, and has driving capability under both voltage levels.
      • For digital signal transmission, when the previous stage acts as an output, it is optimal for the next stage to be in a high-impedance state, as this allows signal transmission to be achieved solely via voltage transfer. If the internal resistance of the load is low, the IO port will be required to output a relatively large current.
    • Pin.OPEN_DRAIN - The pin is configured as an open-drain output
      • The working principle of open-drain output is as follows: when the output value is set to 0, the pin is at a valid low level; when the output value is 1, the pin enters a high-impedance state. That is, it has no driving capability at high level, and an external pull-up resistor is required to realize external driving.
      • It is commonly used in scenarios such as level conversion, implementing the "wired-AND" function, and reducing the driving current inside an IC.
    • Pin.ALT - The pin is configured to perform a port-specific alternate function. For pins configured in this manner, all other pin methods (except Pin.init ()) are not applicable (calling them will result in undefined or hardware-specific behavior)
      • Not all ports implement this mode.
    • Pin.ALT_OPEN_DRAIN - Same as Pin.ALT, but the pin is configured as open-drain. Not all ports implement this mode.
    • Pin.ANALOG - The pin is configured as an analog signal input terminal
  • pull Check whether the specified pin is connected to a (weak) pull-up resistor, and the value can be one of the following:
    • None - No pull-up or pull-down resistor, the pin is in a floating state
      • In practical applications, it is not recommended to leave the pins floating, as they are susceptible to interference.
    • Pin.PULL_UP - Enable pull-up resistor
      • An uncertain signal is clamped to a high level through a resistor, which also functions as a current limiter.
    • Pin.PULL_DOWN - Enable pull-down resistor
      • Pull an uncertain signal down to a low level via a resistor, which also functions as a current limiter.
  • value - Only valid for Pin.OUT and Pin.OPEN_DRAIN modes. If specified, it sets the initial output pin value; otherwise, the state of the pin peripheral remains unchanged
  • drive - Specifies the output power of the pin, which can be one of the following: Pin.LOW_POWER, Pin.MED_POWER, or Pin.HIGH_POWER. The actual current driving capability depends on the port. Not all ports support this parameter.
  • alt - Assigns an alternate function to the pin; the available values depend on the port.

    This parameter is only valid for Pin.ALT and Pin.ALT_OPEN_DRAIN modes. It can be used when a pin supports multiple alternate functions; if a pin only supports one alternate function, this parameter is not required. Not all ports implement this parameter.

As mentioned above, the Pin class allows setting alternate functions for a specific pin, but it does not specify any further operations on such pins. Generally, when configuring a peripheral that requires GPIO, for example, when initializing a UART, the constructor of the corresponding pin will be automatically called for initialization.

2.2 Other Methods of the machine.Pin Class

Method

Description

Pin.init

(mode=- 1, pull=- 1, *, value, drive, alt)

Reinitialize the pin with the given parameters.

Only the specified parameters will be configured, while the status of other pin peripherals will remain unchanged.

Pin.value([x])

This method allows setting and getting the value of the pin.

Depending on whether x is provided, the parameters are as follows:

  • If the parameter is omitted, this method retrieves the digital logic level of the pin, returning 0 or 1 corresponding to a low-voltage and high-voltage signal respectively. The behavior of this method depends on the pin mode:
    • Pin.IN - This method returns the actual input value currently present on the pin
    • Pin.OUT - The behavior and return value of this method are undefined
    • Pin.OPEN_DRAIN - If the pin is in state "0", the behavior and return value of this method are undefined; otherwise, if the pin is in state "1", this method returns the actual input value currently present on the pin.
  • If a parameter is provided, this method sets the digital logic level of the pin. The parameter x can be anything that can be converted to a Boolean value. If converted to True, the pin is set to state "1"; otherwise, it is set to state "0". The behavior of this method depends on the pin's mode:
    • Pin.IN - This value is stored in the output buffer of the pin. The pin status remains unchanged and stays in a high-impedance state. Once the mode is changed to Pin.OUT or Pin.OPEN_DRAIN, the stored value will be activated on the pin.
    • Pin.OUT - The output buffer is immediately set to the specified value
    • Pin.OPEN_DRAIN - If the value is "0", the pin is set to a low-voltage state; otherwise, the pin is set to a high-impedance state.

When setting a value, this method returns None.

Pin.__call__([x])

Pin objects are callable.

The `call` method provides a quick shortcut to set and get the value of a pin. It is equivalent to `Pin.value ([x])`.

Pin.on()

Set the pin to high-level output.

Pin.off()

Set the pin to low-level output.

Pin.irq(handler=None, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, *, priority=1, wake=None, hard=False)

A function for configuring external interrupts for GPIO pins.

When the pin modes differ, the trigger sources of external interrupts also vary:

  • Pin.IN - The trigger source is the external value on the pin
  • Pin.OUT - The trigger source is the output buffer of the pin
  • Pin.OPEN_DRAIN - The trigger source is the output buffer in state "0" and the external pin value in state "1"

The parameters of the Pin.irq method are defined as follows:

  • handler - interrupt callback function, which is invoked when an interrupt is triggered; a Pin instance can be passed into this callback function
  • trigger configures the event that can generate an interrupt. The possible values are:
    • Pin.IRQ_FALLING - Falling Edge Interrupt
    • Pin.IRQ_RISING - Rising Edge Interrupt
    • Pin.IRQ_LOW_LEVEL - Low Level Interrupt
    • Pin.IRQ_HIGH_LEVEL - High Level Interrupt

    These values can trigger multiple events through an OR operation.

  • priority Set the priority of the interrupt. The available priority levels vary depending on the specific chip (external interrupt priority setting is not supported on Raspberry Pi Pico). Meanwhile, the larger the value of priority, the higher the priority of the external interrupt for the corresponding IO pin
  • wake Select this interrupt to wake up the system's power mode.

    It can be IDLE, SLEEP or DEEPSLEEP. These values can also be ORed so that a pin can generate an interrupt in more than one power mode.(External interrupt wake-up is not supported on Raspberry Pi Pico.)

  • hard If true, hardware interrupts are used.

    This reduces the latency between a pin change and the invoked handler. Hard interrupt handlers may not allocate memory

This method returns a callback object.

Pin.low()

Set the pin to low-level output.

Pin.high()

Set the pin to high-level output.

Pin.mode([mode])

Gets or sets the pin mode.

Pin.pull([pull])

Gets or sets the pull-up state of the pin.

Pin.drive([drive])

Get or set the pin drive strength.

The Raspberry Pi Pico does not support the configuration of drive strength.

2.3 Constructor method of the machine.Signal class

The Signal class is a further encapsulation of the Pin class. With the Signal class, we can configure whether to invert the logic of a specific pin (simply put, originally we set high level as logic 1 and low level as logic 0; after inversion, we can set high level as logic 0 and low level as logic 1), thus logically separating the control from the actual physical quantity.

For example, in the following two schemes of MCU controlling LED with different circuit connections, if you directly use Pin for control, you need to use respectively: led_pin (1), led_pin (0) to turn on the LED.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

After using the Signal class, we can use the same method (e. g., led_pin (1)) to control the lighting of the LED without paying attention to the differences in external connection circuits. By using the Signal class, we can ignore the specific physical distinction between high and low levels, so that our program only needs to modify some parameters in the Signal class to run without difference on most circuit boards with different connection modes of external device circuits without generating BUGs.

The Signal class is applicable to the following application scenarios:

There are two types of constructors for Signal:

class machine.Signal(pin_arguments..., *, invert=False)

The parameters are defined as follows:

  • pin_arguments are the same arguments that can be passed to the Pin constructor function
  • invert If set to true, the signal will be inverted (active low)

class machine.Signal(pin_obj, invert=False)

The parameters are defined as follows:

  • pin_obj is the existing Pin object
  • invert If set to true, the signal will be inverted (active low)

2.4 Other Methods of the machine.Signal Class

Method

Description

Signal.value([x])

This method allows setting and getting the value of a signal, depending on whether an argument x is provided:

  • If the parameter is omitted, this method obtains the signal level: 1 indicates a valid signal, and 0 indicates an invalid signal
  • If there is a parameter, this method sets the signal level: The parameter x can be anything that can be converted to a boolean value; if the conversion results in True, the signal is active, otherwise it is inactive.

The correspondence between a signal being active and the actual logic level on the underlying pin depends on whether the signal is inverted (active-low): for non-inverted signals, the active state corresponds to logic 1 and the inactive state corresponds to logic 0; for inverted signals, the active state corresponds to logic 0 and the inactive state corresponds to logic 1.

Signal.on()

activation signal

Signal.off()

Deactivation Signal

3. Application Examples

3.1 GPIO Read/Write Example

In the following experiment, we use Fengya No. 1 Board - Universal Compatible Expansion Board.

In the following code, we first import the Pin class and the time class. In the initialization configuration, we set GPIO 22 as the button input pin, set GPIO 25 as the LED output pin, and enable the pull-down resistor.

In the main loop, continuously detect whether the key is pressed:

The 50ms delay here is mainly due to the contact bounce phenomenon that occurs when a key is closed and opened, as shown in the figure below:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
Button bounce diagram

The actual waveform has a jitter of 50ms around the moment when the key is pressed, so here we skip the jitter area by delaying for 50ms to obtain the level in the intermediate stable area.

The sample code is as follows, located in the folder of the supporting materials: elegance-devkit v1\Demo\01 GPIO_ReadWrite:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time    : 2024/6/12 1:34 PM
# @Author  : Li Qingshui
# @File    : main.py
# @Description : GPIO read/write experiment: drive the onboard LED and read a button

# ======================================== Import Modules ========================================

# Hardware-related modules
from machine import Pin
# Time-related modules
import time

# ======================================== Global Variables ============================================

# Initialize the LED state to off (False)
led_state = False

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("FreakStudio: Using GPIO to control LED and read KEY")

# Note that the constructor of the Pin class in MicroPython does not support keyword arguments, only positional arguments
# Therefore, defining KEY as follows will produce an error
# TypeError: function missing 1 required positional arguments
# key = Pin(id = 2, mode = Pin.IN, pull = Pin.PULL_DOWN)

# Set GPIO 22 as the button input pin
KEY = Pin(22, Pin.IN)
# Set GPIO 25 as the LED output pin, pull-down resistor enabled
LED = Pin(25, Pin.OUT, Pin.PULL_DOWN)

# ========================================  Main Program  ============================================

# Loop to detect whether the button is pressed
while True:
    # KEY pin press detected
    if KEY.value() == 0:
        # Button debounce: delay 50 ms to skip the bouncing period
        time.sleep_ms(50)
        # Make sure the button is still pressed
        if KEY.value() == 0:
            # Toggle the LED state
            led_state = not led_state
            # Set the LED on or off according to the state variable
            if led_state:
                LED.on()
                print("The LED is ON")
            else:
                LED.off()
                print("The LED is OFF")
            # Wait for the button to be released (avoid detecting repeated presses)
            while KEY.value() == 0:
                pass

It should be noted here that MicroPython does not support keyword arguments when passing parameters to the constructor of the Pin class, and only supports positional arguments, so the following definition of KEY will throw an error TypeError: function missing 1 required positional arguments:

KEY = Pin(id = 2, mode = Pin.IN, pull = Pin.PULL_DOWN)

Burn the above code into MicroPython, and you can observe the experimental phenomenon:

When the key is pressed for the first time, toggle led_state to True, the LED will light up and the terminal outputs the following:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

When the button is pressed a second time, toggle led_state to False, the LED turns off and the terminal outputs the following:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

After that, each time a key is pressed, the status of the LED toggles alternately between on and off.

3.2 GPIO External Interrupt Example

In the following experiment, we use Fengya No. 1 Board - Universal Compatible Expansion Board.

When using external interrupts, we need to specify which pins are used for interrupts, the conditions for triggering the interrupts, and the operations to be performed after the interrupts are responded to.

In the following code, we set GPIO22 as a key input pin with pull-up resistor enabled, configure GPIO22 to generate a falling-edge triggered interrupt, and execute the handle_interrupt function after the interrupt is responded to, toggle the value of led_state and the status of the LED, and print the LED status information during the interrupt.

In the main program's while loop, debug information is output "Waiting for button press. ..". The main loop will not interfere with the execution of interrupts, which are triggered by hardware and respond in real time.

The sample code is located in the folder of the supporting materials as follows: elegance-devkit v1\Demo\02 GPIO_EXTI:

# Python env   : MicroPython v1.23.0              
# -*- coding: utf-8 -*-        
# @Time    : 2024/6/14 11:10 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : GPIO external interrupt experiment: press the button to toggle the LED on/off

# ======================================== Import Modules ========================================

# Hardware-related modules
from machine import Pin
# Time-related modules
import time

# ======================================== Global Variables ============================================

# LED state flag: True means on, False means off
led_state: bool = False

# ======================================== Functions ============================================

def handle_interrupt(pin: Pin) -> None:
    """
    Callback function for the GPIO external interrupt, used to toggle the LED on/off state.

    After the interrupt is triggered, button debouncing is performed first. After confirming the button is still pressed,
    the LED is toggled on or off according to its current state, and the state information is printed.

    Args:
        pin (Pin): The GPIO pin instance that triggered the interrupt.

    Returns:
        None
    """
    # Declare global variables
    global LED
    global led_state

    # Debounce: delay 50 ms
    time.sleep_ms(50)

    # Confirm again that the button is still pressed (GPIO pin level is low)
    if pin.value() == 0:
        # Toggle the LED state
        led_state = not led_state
        if led_state:
            # LED on
            LED.on()
            print("The LED is ON")
        else:
            # LED off
            LED.off()
            print("The LED is OFF")

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("FreakStudio: Using GPIO EXTI interrupt to toggle LED")

# Set GPIO 22 as the button input pin, pull-up resistor enabled
KEY = Pin(22, Pin.IN, Pin.PULL_UP)
# Set GPIO 25 as the LED output pin, pull-down resistor enabled
LED = Pin(25, Pin.OUT, Pin.PULL_DOWN)

# Configure the KEY interrupt: the callback is handle_interrupt, triggered on the falling edge
KEY.irq(handler=handle_interrupt, trigger=Pin.IRQ_FALLING)

# ======================================== Main Program ============================================

# Main loop: output button state information while the program is idle
while True:
    # Wait for the interrupt to trigger, print debug information
    print("Waiting for button press...")
    time.sleep(1)

Burn the code and open the terminal, then you can see the following output in the terminal when no button is pressed:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

When the key is pressed, the LED lights up; when pressed again, the LED turns off. The experimental phenomenon is similar to that of the GPIO read-write routine in Section 3.1.

When the button is pressed for the first time:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

When the button is pressed for the second time:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Here, we have added type annotations to the code and complied with the PEP8 specification. The so-called type annotation is a mechanism in Python used to specify the data types of variables, function parameters and return values. Simply put, it explicitly tells others or program tools in the code what type a certain variable, function parameter or return value is (such as integer, string, list, etc.). It is like making notes for variables and functions. For example, if you define a function that receives a number but someone passes in a text, the type annotation can warn you in advance where the problem is.

For more information on type annotations, you can refer to the following articles:

Meanwhile, all our code complies with the PEP8 specification, PEP8 is a style guide for the Python programming language, whose full name is "Python Enhancement Proposal 8"(Python Enhancement Proposal No. 8). It is a document that specifies the best practices and formatting requirements for writing Python code. Simply put, it is a set of code writing rules, similar to the formatting requirements for writing an essay.It teaches you how to format your code to be neater and more readable, for example, using lowercase letters with underscores for variable names, leaving two blank lines between functions, keeping each line of code under 79 characters, and so on. Its goal is to make the code everyone writes have a consistent style, look more comfortable, and be easier to maintain and collaborate on at the same time.

For more details about the PEP8 style guide, please refer to the following article:

3.3 Signal Class Routines

In the following experiment, we need to insert the Fengya No. 1 Board - Colorful Touch Expansion Board into the Fengya No. 1 Board - Universal Compatible Expansion Board:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

In the following routine, we use the Signal class to control two LEDs connected to different circuits, where GP17 is connected to an LED whose cathode is tied to ground, so the corresponding GPIO lights it up by outputting a high level; while GP16 is connected to an LED whose anode is tied to + 3V3, so the corresponding GPIO lights it up by outputting a low level. We use the Signal class to wrap the existing Pin object, ultimately achieving control over the LED via the same method.

The code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/6/21 10:32 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : Signal class experiment: control two LEDs connected with different circuits

# ======================================== Import Modules ========================================

# Hardware-related modules
from machine import Pin, Signal
# Time-related modules
import time

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# ======================================== Initialization ==========================================

# Power-on delay
time.sleep(3)
# Print debug information
print("FreakStudio : Signal Class Test")

# Set GPIO 17 as the LED1 (common anode) output pin, pull-down resistor enabled
LED1_Pin = Pin(17, Pin.OUT, Pin.PULL_DOWN)
# Set GPIO 16 as the LED2 (common cathode) output pin, pull-down resistor enabled
LED2_Pin = Pin(16, Pin.OUT, Pin.PULL_DOWN)

# ========================================  Main Program  ============================================

# Without the Signal class, using the Pin class directly requires accounting for differences in the external circuits, and different levels are needed to turn on the LEDs
# LED1 turns on with a high-level input
LED1_Pin.value(1)
# LED2 turns on with a low-level input
LED2_Pin.value(0)

# Wrap the existing Pin objects with the Signal class
# LED1_Pin is not inverted: high level = 1, low level = 0
LED1 = Signal(LED1_Pin, invert=False)
# LED2_Pin is inverted: high level = 0, low level = 1
LED2 = Signal(LED2_Pin, invert=True)

# Now one method can turn on both LEDs
LED1.on()
LED2.on()

# Wait for 5 s
time.sleep(5)

# Get the signal state
print("LED 1 value :", LED1.value())
print("LED 2 value :", LED2.value())

# Get the pin state
print("LED1_Pin value :", LED1_Pin.value())
print("LED2_Pin value :", LED2_Pin.value())

# Turn off both LEDs
LED1.off()
LED2.off()

# Wait for 1 s
time.sleep(1)

# Get the signal state
print("LED 1 value :", LED1.value())
print("LED 2 value :", LED2.value())

# Get the pin state
print("LED1_Pin value :", LED1_Pin.value())
print("LED2_Pin value :", LED2_Pin.value())

Burn the code, open the terminal, and use mpremote to connect to the Raspberry Pi Pico, you will see the following output:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

We can see that on the Elegance No. 1 Board - Colorful Touch Expansion Board, the HIGHLED and LOWLED are lit up simultaneously first, and then turned off at the same time:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

3.3 Application Experiment.mp4 19.5 MB

3.4 Stepper Motor Control via GPIO

3.4.1 Basic Knowledge of Stepper Motor

A stepper motor is a special type of electric motor that converts input electrical pulse signals into discrete changes in angle or position, thereby enabling precise angle control. Stepper motors mainly have the following characteristics:

Stepper motors are widely used in various automated equipment, such as printers, computer numerical control machine tools, robots, 3D printers, etc. , and are an ideal choice for achieving precise position control. By controlling the frequency and sequence of pulse signals, the speed, angle and direction of the motor can be accurately controlled.

Here, the motor model we use is 28BYJ-48 5-wire 4-phase stepper motor:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

It has the following main features:

This 28BYJ-48 stepper motor is widely used in various small electromechanical devices, such as door locks, toys, automation equipment, etc. Thanks to its compact size, low power consumption and sufficient torque, it is extremely suitable for use with microcontrollers. The working principle of the 28BYJ-48 5-wire 4-phase stepper motor can be briefly described as follows: by controlling the on-off of a total of 4 pairs (8) of windings on the stator (the two windings directly opposite each other are always turned on or off simultaneously), the electromagnetic force generated when the windings are energized attracts the 6 teeth made of permanent magnet material on the rotor, so as to control the rotation of the intermediate rotor.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Here, when driving the 28BYJ-48 stepper motor, it is necessary to use a ULN2003 driver IC. The ULN2003 is a common 7-channel switch driver integrated circuit. We can use GPIO to drive the internal Darlington transistors (A Darlington transistor, also called a composite transistor, is formed by combining two triodes into one to provide a larger driving current for driving heavy loads) to control their on-off, so as to realize the control of high-current motor operation with low-current GPIO output. It is mainly used to drive different types of electronic loads, such as stepper motors, relays, LEDs and other small electromagnetic devices.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The ULN2003 is available in two packages: DIP-16 through-hole and SOP-16 surface-mount.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The main control methods for stepper motors are as follows:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

3.4.2 Application Experiment

Here, we adopt the single-phase drive mode to drive the stepping motor. Simply put, the principle of the single-phase drive mode is as follows:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft
  1. 4-phase winding structure: The 28BYJ-48 stepper motor has 4 independent winding phases, which are controlled by the four pins IN1, IN2, IN3 and IN4 respectively.
  2. Sequential energization drive: By energizing these four phase windings in sequence, the stepper rotation of the rotor can be achieved. Each time the on-off state of one phase winding is switched, the rotor moves by one step angle.
  3. Hysteresis Structure: The rotor adopts a hysteresis structure, that is, the rotor is composed of a ring of permanent magnets, while the stator consists of 4 electromagnet windings. When a certain phase winding of the stator is energized, a magnetic pole will be generated, which attracts or repels the magnetic poles of the rotor, thus driving the rotor to rotate.
  4. Deceleration mechanism: The 28BYJ-48 has a built-in deceleration mechanism, which reduces the step angle from the motor's inherent 7.5° to 0.0625°, thus greatly improving the angular resolution.

Here, we use the long pin headers on the Fengya No. 1 Board - Universal Compatible Expansion Board to connect to the logic input interfaces on the Fengya No. 1 Board - Stepper Motor Driver Board, and the pins used are shown in the following table:

microcontroller pin

Motor drive pin

Stepper motor pins

GPIO2

IN1

A

GPIO3

IN2

B

GPIO4

IN3

C

GPIO5

IN4

D

GND

GND

NC

VBUS

VCC

COMMON

Then connect the interface of the logic output section on the stepper motor driver board to the stepper motor:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Meanwhile, toggle on the DIP switches on the Fengya No. 1 Board - Stepper Motor Driver Board:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The overall connection is shown in the following figure:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The sample code is as follows, which can be found in the folder of the supporting materials: elegance-devkit v1\Demo\04 GPIO_StepMotor

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time        : 2024/7/27 10:23 AM
# @Author      : Li Qingshui
# @File        : main.py
# @Description : GPIO class experiment: control a stepper motor via GPIO

# ======================================== Import Modules ========================================

# Hardware-related modules
from machine import Pin
# Time module
import time

# ======================================== Global Variables ============================================

# Initialize the GPIO pin tuple; each element is a Pin object
pins: tuple[Pin, ...] = (
    Pin(2, Pin.OUT),
    Pin(3, Pin.OUT),
    Pin(4, Pin.OUT),
    Pin(5, Pin.OUT)
)

# ======================================== Functions ============================================

def control_step_motor(step: int) -> None:
    """
    Controls the stepping logic of the stepper motor.

    According to the current step index, the corresponding pin is driven high and the other pins are driven low,
    implementing sequential control of the stepper motor.

    Args:
        step (int): Current step index, in the range 0 ~ 3.

    Returns:
        None
    """
    for index, pin in enumerate(pins):
        # The pin whose index equals the current step value is driven high; the other pins are driven low
        pin.value(index == step)

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("FreakStudio: Using GPIO to control step motor")

# ======================================== Main Program =============================================

while True:
    # Iterate over the 4 step values 0 ~ 3
    for step in range(4):
        # Call the step control function
        control_step_motor(step)
        # Delay 4 ms for each step
        time.sleep_ms(4)

Burn the code, and you will see the stepper motor rotate while the indicator lights on the stepper motor driver module light up in sequence.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

February 14.mp4 8.6 MB

Here, you can refer to the following link for the knowledge points related to the Python tuple data structure:

For a detailed explanation of the driving principle of unipolar stepper motors, please refer to the following video:

[From hardware to Code] Complete Guide to I2C Bus Unipolar Stepper Motor Driver Board Design | Standardized Interface + Motor Principles + Practical Testing, This One Article Has You Covered!_Bilibili_bilibili

3.5 Rotary Encoder Experiment

3.5.1 Basic Knowledge of Rotary Encoder

Here, we use the EC11 rotary encoder component with 20 pulses and 20 positioning points, and its structure is as follows:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The names and functions of the respective components are as follows:

EC11 typically has 5 pins, as shown in the following figure:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Its working principle is as follows: the EC11 outputs incremental rotation signals through two signal channels (pins A and B). During rotation, the A and B signal channels generate interleaved pulses, and the rotation direction (clockwise or counterclockwise) can be determined by comparing the phase relationship between the two:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Simply put, it means:

It is not difficult to find that whenever a level transition occurs in Phase A or Phase B, the rotation direction can be determined simply by detecting the state of the other phase:

Meanwhile, the number of rotation steps (increment) can be determined in combination with pulse counting.

Here, the EC11 rotary encoder also comes with a push switch (pins D and E): when the encoder is pressed, its internal mechanical structure triggers a key signal, which is typically used for control or operation confirmation.

3.5.2 Application Experiment

In the following code, we have customized an EC11Encoder class, which reads the rotation steps and button status of the rotary encoder through interrupt processing, and updates the Progress Bar on the terminal in the main program loop to display the rotation degree of the rotary encoder.

Here, we need to insert the Fengya No. 1 Board - Universal Compatible Expansion Board into the Fengya No. 1 Board - LCD Screen Human-Machine Interaction Board, and turn on the RE-CLK, RE-DT and RE-SW on the DIP switch SWITCH2. The physical connection diagram is shown below:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

The wiring of the components is as follows:

EC11 Pin Functions

Raspberry Pi Pico pins

Description

VCC (+3.3V)

3V3(OUT)

Power supply voltage, connect to the 3.3V power output of the Pico

GND

GND

common ground wire

Phase A

GPIO26

Encoder rotation signal A, for phase detection

Phase B

GPIO27

Encoder rotation signal B, for phase detection

Pushbutton SW

GPIO21

Encoder pushbutton switch, outputs low level when pressed

The sample code is as follows, located in the folder of the supporting materials: elegance-devkit v1\Demo\05 GPIO_RotaryEncoder:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-
# @Time    : 2024/9/18 10:44 PM
# @Author  : Li Qingshui
# @File    : main.py
# @Description : GPIO class experiment: read the value of a rotary encoder

# ======================================== Import Modules =========================================

# Import hardware-related modules
from machine import Pin
# Import time-related modules
import time

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

class EC11Encoder:
    """
    EC11 rotary encoder class, used to read the rotary encoder signals through GPIO pins, detect the rotation direction and count, and respond to button events.

    This class uses GPIO pins to read the A-phase and B-phase signals of the rotary encoder, and determines the rotation direction based on the rising edge of the A-phase signal and the state of the B-phase signal.
    It also monitors button press and release events on the button pin, which are used to reset the rotation count. Each button press clears the counter,
    so that the device can be reset with the button.

    Attributes:
        pin_a (Pin): GPIO pin object for the A-phase signal. Used to read the rotary encoder signal.
        pin_b (Pin): GPIO pin object for the B-phase signal. Used together with the A-phase signal to determine the rotation direction.
        pin_btn (Pin): GPIO pin object for the button signal. Used to detect button press and release.

        rotation_count (int): Rotation counter that records the number of rotation steps of the rotary encoder. A positive value means clockwise rotation, and a negative value means counterclockwise rotation.
        last_state_a (int): The A-phase signal state read last time. Used to determine the rotation direction.
        button_pressed (bool): Whether the button is pressed. True if the button is pressed, otherwise False.

    Methods:
        get_rotation_count(): Get the current rotation count.
        reset_rotation_count(): Reset the rotation counter.
        is_button_pressed(): Check whether the button is pressed.
        _handle_rotation(pin: Pin): Internal interrupt handler that processes the rotation signal and updates the rotation count.
        _handle_button(pin: Pin): Internal interrupt handler that detects button press and release events.
    """

    def __init__(self, pin_a: int, pin_b: int, pin_btn: int) -> None:
        """
        Initialize the EC11 rotary encoder.

        Args:
            pin_a (int): GPIO pin number for the A-phase signal.
            pin_b (int): GPIO pin number for the B-phase signal.
            pin_btn (int): GPIO pin number for the button signal.
        """
        self.pin_a = Pin(pin_a, Pin.IN)
        self.pin_b = Pin(pin_b, Pin.IN)
        self.pin_btn = Pin(pin_btn, Pin.IN, Pin.PULL_UP)

        # Rotation counter
        self.rotation_count = 0
        # Previous state of phase A
        self.last_state_a = self.pin_a.value()
        # Whether the button is pressed
        self.button_pressed = False

        # Set up interrupt handling
        self.pin_a.irq(trigger=Pin.IRQ_RISING, handler=self._handle_rotation)
        self.pin_btn.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)

    def _handle_rotation(self, pin: Pin) -> None:
        """
        Interrupt callback that detects the rotation direction of the rotary encoder.

        Triggered on the rising edge of phase A, and reads the state of phase B to determine the rotation direction.

        Args:
            pin (Pin): The phase A signal pin that triggered the interrupt.
        """
        current_state_b = self.pin_b.value()

        # Clockwise rotation
        if current_state_b == 0:
            self.rotation_count += 1
        # Counterclockwise rotation
        else:
            self.rotation_count -= 1

    def _handle_button(self, pin: Pin) -> None:
        """
        Interrupt callback that detects button press and release.

        Updates the state when the button is pressed, and resets the rotation counter when it is released.

        Args:
            pin (Pin): The button signal pin that triggered the interrupt.
        """
        # Button pressed
        if self.pin_btn.value() == 0:
            self.button_pressed = True
        # Button released
        else:
            self.button_pressed = False
        # Reset the rotation counter
        self.rotation_count = 0

    def get_rotation_count(self) -> int:
        """
        Get the current rotation count.

        Returns the rotation count; a positive value means clockwise, a negative value means counterclockwise.

        Returns:
            int: The current rotation count.
        """
        return self.rotation_count

    def reset_rotation_count(self) -> None:
        """
        Reset the rotation counter.

        Sets the rotation counter to zero.
        """
        self.rotation_count = 0

    def is_button_pressed(self) -> bool:
        """
        Detect whether the button is pressed.

        Returns the button state: True if the button is pressed, False if not.

        Returns:
            bool: Whether the button is pressed.
        """
        return self.button_pressed

# Terminal progress bar class
class ProgressBar:
    """
    Terminal progress bar class, used to display an updatable progress bar in the terminal.

    This class shows the progress of the current task by drawing a progress bar in the terminal. It supports dynamic updates of the progress bar and allows the user to
    customize the maximum value and the length of the bar. The bar uses green for the completed part and red for the remaining part.

    Attributes:
        max_value (int): Maximum value of the progress bar, representing the total progress of the task. When the current progress reaches this value, the bar shows 100%.
        bar_length (int): Total length of the progress bar, used to control its width. Defaults to 50.

    Methods:
        update(current_value: int) -> None: Updates the progress bar display; takes the current progress value.
        reset() -> None: Resets the progress bar to 0%, showing an all-red bar.
    """
    
    def __init__(self, max_value: int, bar_length: int = 50) -> None:
        """
        Initialize the progress bar.

        Args:
            max_value (int): Maximum value of the progress bar. The bar shows 100% when this value is reached.
            bar_length (int): Total length of the progress bar. Defaults to 50.
        """
        self.max_value = max_value
        self.bar_length = bar_length

    def update(self, current_value: int) -> None:
        """
        Update the progress bar.

        Calculates and updates the progress bar display based on the current value, ensuring the current value does not exceed the maximum value.

        Args:
            current_value (int): Current value of the progress bar.
        """
        if current_value > self.max_value:
            current_value = self.max_value
        if current_value < 0:
            current_value = 0

        progress = current_value / self.max_value
        block = int(self.bar_length * progress)

        # Green indicates progress, red indicates the remainder
        bar = '\033[92m' + '█' * block + '\033[91m' + '-' * (self.bar_length - block) + '\033[0m'
        print(f"\r[{bar}]", end='')

    def reset(self) -> None:
        """
        Reset the progress bar.

        Resets the progress bar to 0%, i.e. all red.
        """
        print(f"\r\033[91m[{'-' * self.bar_length}]\033[0m", end='')

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio : GPIO read Rotary Encoder value")

# Create the EC11 rotary encoder object, using GPIO26 and GPIO27 as phase A and phase B, and GPIO21 as the button
encoder = EC11Encoder(pin_a=26, pin_b=27, pin_btn=21)
# Create the terminal progress bar object to display progress; 20 rotations reach 100%
progress_bar = ProgressBar(max_value=20)

# ========================================  Main Program  ===========================================

# Get the rotation count and button state in the main loop
while True:
    # Get the rotation count
    current_rotation = encoder.get_rotation_count()
    # print(f"Rotation count: {current_rotation}")
    # Update the progress bar
    progress_bar.update(current_rotation)
    # When the button is pressed, reset the progress bar
    if encoder.is_button_pressed():
        progress_bar.reset()
    # Update every 10ms
    time.sleep_ms(10)

Here, the core part that detects the rotation count and rotation direction of the rotary encoder is the _handle_rotation method; we configure the pin connected to phase A of the rotary encoder to input mode with rising-edge triggered interrupt, and set its interrupt callback function to the _handle_rotation method:

def _handle_rotation(self, pin: Pin) -> None:
    """
    Interrupt callback that detects the rotation direction of the rotary encoder.

    Triggered on the rising edge of phase A, and reads the state of phase B to determine the rotation direction.

    Args:
        pin (Pin): The phase A signal pin that triggered the interrupt.
    """
    current_state_b = self.pin_b.value()

    # Clockwise rotation
    if current_state_b == 0:
        self.rotation_count += 1
    # Counterclockwise rotation
    else:
        self.rotation_count -= 1

When the rising edge of the phase A signal is detected, the system enters the _handle_rotation method to acquire the state of the phase B signal and make a judgment:

At the same time, we also set the button of the rotary encoder to be triggered on the falling edge, and call the _handle_button method when the button is pressed, in which the button state is updated and the rotation counter is reset.

We use a custom ProgressBar class to dynamically display progress in the terminal. We can dynamically update the display of the Progress Bar via the update method, or call the reset method to reset the Progress Bar to zero for easy restarting of the display. The core code snippet is as follows:

def update(self, current_value: int) -> None:
    """
    Update the progress bar.

    Calculates and updates the progress bar display based on the current value, ensuring the current value does not exceed the maximum value.

    Args:
        current_value (int): Current value of the progress bar.
    """
    if current_value > self.max_value:
        current_value = self.max_value
    if current_value < 0:
        current_value = 0

    progress = current_value / self.max_value
    block = int(self.bar_length * progress)

    # Green indicates progress, red indicates the remainder
    bar = '\033[92m' + '█' * block + '\033[91m' + '-' * (self.bar_length - block) + '\033[0m'
    print(f"\r[{bar}]", end='')

In this code, we ensure that current_value stays within the valid range, i. e., no greater than the maximum value and no less than 0; then we calculate the proportion of the current value to the maximum value to obtain the number of blocks displayed in the Progress Bar.

In the code for building the Progress Bar section:

bar = '\033[92m' + '█' * block + '\033[91m' + '-' * (self.bar_length - block) + '\033[0m'

The meaning of each part is as follows:

Next, we use the Print method to print the Progress Bar, and here we use the carriage return character '\r' to return to the start of the line so as to overwrite the previous Progress Bar output in the terminal; then we add the end parameter with a value of end='' to avoid line breaks after each print, so that the Progress Bar only prints dynamically updated content on the same line.

In the main program section, we continuously read the value of the rotary encoder and update the Progress Bar, and reset the Progress Bar when a key press is detected.

Burn the code, open the terminal, and the following content will be displayed:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

3.5 Application Experiment.mp4 19.0 MB

When we rotate the EC11 encoder clockwise, we can see that the green rectangular box of the Progress Bar increases:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

When we rotate the EC11 encoder counterclockwise, you can see that the green rectangular box of the Progress Bar decreases:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

Here, we may find that when the rotary encoder rotates, the terminal Progress Bar sometimes jumps by several units. The reason is that the count value of the rotary encoder does not only change by one unit each time the rotary encoder rotates. We add the following code in the main loop to print the rotation count value of the rotary encoder:

print(f"Rotation count: {current_rotation}")

Burn the code, run it, and then open the terminal:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft

It can be observed that the count value of the rotary encoder sometimes jumps by several units when it rotates once. This is mainly because, as a mechanical device, when the user rotates the encoder, its contact points will repeatedly make and break contact in a short period of time, causing signal jitter and thus generating redundant count pulses.

To solve this problem, we can use a capacitor or an RC circuit to filter the signal, slow down its rapid changes and smooth out jitter; alternatively, in terms of software, we can judge the signals collected multiple times in a short period of time, and only regard the signal as valid when the same signal is detected for several consecutive times to address this issue.

In the timer chapter, we will use a timer to scan the encoder status every 10ms for debouncing.

Here, you can refer to the following articles for knowledge related to Object Oriented programming and custom classes in Python:

3.6 Five-way Button Experiment

3.6.1 Basic Knowledge of 5-Way Key

A five-way key is a common input device, typically used in the control interfaces of electronic products such as remote controls, game controllers and mobile devices. It contains five contacts inside: one common contact at the center, with multiple fixed contacts distributed around it. Its operating principle relies on the connection between the movable contact reed, the common contact and the surrounding fixed contacts to enable switching between multiple states. When the operating lever is moved, the movable contact reed comes into contact with the corresponding contact, thereby establishing an electrical circuit connection.

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

A 5-way key looks like a single button, but it actually integrates five distinct key states, allowing users to switch between multiple functions by pressing it in different directions. Here, we connect the common contact (COM terminal) of the 5-way key to the + 5V power supply. When none of the keys is pressed, the voltage measured at any of the keys is 0V, since all contacts are in an open-circuit state and no current flows; when any key is pressed, the movable contact reed of that key will connect with the common contact to form a closed circuit, and the voltage measured at the corresponding key will then rise to the supply voltage (5V).

3.6.2 Application Experiment

In the following program, we will use the GPIO pins of the Raspberry Pi Pico to read and process the input status of a 5-way joystick (with 7 buttons), and print the corresponding button information when a button is pressed. Here, we need to insert the Fengya No. 1 Board - Universal Compatible Expansion Board into the Fengya No. 1 Board - LCD Screen Human-Machine Interaction Board, and turn on all the options on the SWITCH3 DIP switch. The physical connection diagram is shown below:

The connection status of the 5-way button is shown in the following table, in which the common terminal (COM terminal) of the 5-way button is connected to the + 3V3 power supply:

5-way button pins

Raspberry Pi Pico pins

Description

COM (Common Terminal)

3V3(OUT)

Common power terminal, connect to the 3.3V power output of the Pico

UP

GPIO20

Up direction key input

DOWN

GPIO18

Down arrow key input

LEFT

GPIO16

Left direction key input

RIGHT

GPIO19

Right direction key input

MID (Confirm Key)

GPIO17

Center button input

Sample code is as follows, located in the folder of the supporting materials: elegance-devkit v1\Demo\06 GPIO_5DJoystick:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2025/1/2 2:10 PM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : GPIO experiment, 5D joystick experiment

# ======================================== Import Modules =========================================

# Import hardware-related modules
from machine import Pin
# Import time-related modules
import time

# ======================================== Global Variables ============================================

# ======================================== Functions ============================================

# ======================================== Custom Classes ============================================

# Custom five-way button class
class DirectionalButton:
    """
    A class for handling the five-way button.

    This class encapsulates the functionality of the five-way button, including detection of the UP, DOWN, LEFT, RIGHT, MID, SET and RST buttons.
    Each button listens for press and release events through its configured GPIO pin. The button states are stored in the `button_state` dictionary.
    When a button state changes, an internal interrupt handler is triggered to update the state. The methods provided include getting the state of a specific button, resetting all button states, and so on.

    Attributes:
        up_pin (Pin): GPIO pin object for the UP button. It is set to input mode with the pull-down resistor enabled during initialization.
        down_pin (Pin): GPIO pin object for the DOWN button. It is set to input mode with the pull-down resistor enabled during initialization.
        left_pin (Pin): GPIO pin object for the LEFT button. It is set to input mode with the pull-down resistor enabled during initialization.
        right_pin (Pin): GPIO pin object for the RIGHT button. It is set to input mode with the pull-down resistor enabled during initialization.
        mid_pin (Pin): GPIO pin object for the MID button. It is set to input mode with the pull-down resistor enabled during initialization.
        set_pin (Pin): GPIO pin object for the SET button. It is set to input mode with the pull-down resistor enabled during initialization.
        rst_pin (Pin): GPIO pin object for the RST button. It is set to input mode with the pull-down resistor enabled during initialization.
        button_state (dict): Button state dictionary that records the current state of each button. The keys are button names and the values are button states (True for pressed, False for not pressed).

    Methods:
        get_button_state(button): Gets the current state of the specified button. Returns True if pressed, False if not pressed.
        reset_all(): Resets the state of all buttons, setting all button flags to False (not pressed).
        _handle_button(pin): Button interrupt handler that sets the button state according to the button's pin.
    """

    def __init__(self, up_pin: int, down_pin: int, left_pin: int, right_pin: int,
                 mid_pin: int, set_pin: int = None, rst_pin: int = None) -> None:
        """
        Initialize the five-way button class, configuring the GPIO pins of all buttons and enabling the built-in pull-up resistors.

        Args:
            up_pin (int): GPIO pin for the UP button.
            down_pin (int): GPIO pin for the DOWN button.
            left_pin (int): GPIO pin for the LEFT button.
            right_pin (int): GPIO pin for the RIGHT button.
            mid_pin (int): GPIO pin for the MID button.
            set_pin (int): GPIO pin for the SET button.
            rst_pin (int): GPIO pin for the RST button.

        Returns:
            None
        """
        # Initialize the button pins for each direction, set them to input mode, and enable the pull-down resistors
        self.up_pin     = Pin(up_pin, Pin.IN, Pin.PULL_DOWN)
        self.down_pin   = Pin(down_pin, Pin.IN, Pin.PULL_DOWN)
        self.left_pin   = Pin(left_pin, Pin.IN, Pin.PULL_DOWN)
        self.right_pin  = Pin(right_pin, Pin.IN, Pin.PULL_DOWN)
        self.mid_pin    = Pin(mid_pin, Pin.IN, Pin.PULL_DOWN)

        if set_pin is not None and rst_pin is not None:
            self.set_pin    = Pin(set_pin, Pin.IN, Pin.PULL_DOWN)
            self.rst_pin    = Pin(rst_pin, Pin.IN, Pin.PULL_DOWN)

        # Initialize the button state dictionary, with a default value of False (not pressed)
        self.button_state = {
            'UP': False,
            'DOWN': False,
            'LEFT': False,
            'RIGHT': False,
            'MID': False,
            'SET': False,
            'RST': False
        }

        # Set the interrupt handler for each button pin
        self.up_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)
        self.down_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)
        self.left_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)
        self.right_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)
        self.mid_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)

        if set_pin is not None and rst_pin is not None:
            self.set_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)
            self.rst_pin.irq(trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, handler=self._handle_button)

    def _handle_button(self, pin: Pin) -> None:
        """
        Button interrupt handler that sets the button state according to the button's pin.

        Updates the state of the corresponding button each time a button is pressed or released.

        Args:
            pin (Pin): The button pin that triggered the interrupt.

        Returns:
            None
        """
        if pin == self.up_pin:
            self.button_state['UP'] = (pin.value() == 1)
        elif pin == self.down_pin:
            self.button_state['DOWN'] = (pin.value() == 1)
        elif pin == self.left_pin:
            self.button_state['LEFT'] = (pin.value() == 1)
        elif pin == self.right_pin:
            self.button_state['RIGHT'] = (pin.value() == 1)
        elif pin == self.mid_pin:
            self.button_state['MID'] = (pin.value() == 1)
        elif pin == self.set_pin:
            self.button_state['SET'] = (pin.value() == 1)
        elif pin == self.rst_pin:
            self.button_state['RST'] = (pin.value() == 1)

    def get_button_state(self, button: str) -> bool:
        """
        Get the current state of the specified button.

        Checks whether the specified button is pressed.

        Args:
            button (str): The button to query. Supports 'UP', 'DOWN', 'LEFT', 'RIGHT', 'MID', 'SET', 'RST'.

        Returns:
            bool: Returns the state of the specified button. True means pressed, False means not pressed.
        """
        return self.button_state.get(button, False)

    def reset_all(self) -> None:
        """
        Reset the state of all buttons to not pressed.

        Used when the state of all buttons needs to be cleared in certain scenarios.

        Args:
            None

        Returns:
            None
        """
        for button in self.button_state:
            self.button_state[button] = False

# ======================================== Initialization ==========================================

# Power-on delay of 3 s
time.sleep(3)
# Print debug information
print("FreakStudio : GPIO read 5D Joystick value")

# Create the five-way button object, using GPIO 16 to GPIO 20 to connect the buttons
button = DirectionalButton(up_pin=20, down_pin=18, left_pin=16, right_pin=19, mid_pin=17)

# ========================================  Main Program  ===========================================

# Main loop: read the button states and print them
while True:
    # Check whether any button is pressed
    for button_name in ['UP', 'DOWN', 'LEFT', 'RIGHT', 'MID', 'SET', 'RST']:
        # If a button is pressed, print the button name and state
        if button.get_button_state(button_name):
            print(f"{button_name} button is pressed.")

    # Loop every 100 milliseconds
    time.sleep(0.1)

DirectionalButton class encapsulates the detection and status management for the 7 buttons (UP, DOWN, LEFT, RIGHT, MID, SET, RST) of the 5-way joystick. Each button corresponds to a GPIO pin, and the button status is detected in real time via interrupt, with the following methods:

In the main loop, we create an instance of the DirectionalButton class, and pass the pin numbers to the corresponding button pins. Here, GPIO pins 16 to 22 of the Raspberry Pi Pico are used to connect the various buttons of the joystick, and in the main loop, the program continuously checks the state of each button;For each button, call the get_button_state () method to get its current state. If the button is pressed, print the relevant information (e. g., "UP button is pressed. "). After each loop iteration, use time.sleep (0.1) to add a 100-millisecond delay, so as to avoid reading the button state too frequently and reduce the CPU load.

Burn the program, open the terminal, and the following content will be displayed:

04 GPIO General Purpose Input/Output —— Document Tutorial Draft
04 GPIO General Purpose Input/Output —— Document Tutorial Draft

It can be seen that when different keys are pressed, the status information of the corresponding key can be displayed.

References

https://www.renesas.com/us/en/support/engineer-school/mcu-programming-peripherals-01-gpio

https://en.wikipedia.org/wiki/General-purpose_input/output

https://blog.csdn.net/zhuoqingjoking97298/article/details/121704275

https://www.skyone.host/2021/micropython-interrupt

https://mpython.readthedocs.io/zh/master/reference/isr_rules.html

http://www.86x.org/en/latet/library/machine.Signal.html

https://blog.csdn.net/zhuoqingjoking97298/article/details/121625627

http://www.taichi-maker.com/homepage/reference-index/motor-reference-index

https://wiki.lckfb.com/zh-hans/dkx-stm32f103c8t6/module/sensor/ec11.html

Version Record

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/16

Document initialized, based on MicroPython version V1.23.0.

v1.0.1

Li Zisheng

2025/09/16

Edit some images.

v1.1.0

Li Zisheng

2025/12/20

Supplement basic knowledge to complete this document.

v1.2.0

Li Zisheng

2026/02/14

Improve the stepper motor section.