Labs / MicroPython tutorials

06 Interrupt —— First Draft of Document Tutorial

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

Contents

1 Basic Concepts and Types of Interrupts

1.1 Basic Concepts of Interrupts

Here, we use an example to illustrate the concept and function of interrupts. Imagine the previous routine where we used a serial peripheral to receive data: we needed to constantly use the UART.any () method to check whether there is data available for reading from the outside. This approach works only when the code flow is simple and the number of peripheral calls is small. However, if we add code to the original program such as driving an LCD screen to display data, performing digital filtering on motion data, interacting with a PC via the USB protocol, and saving program runtime logs to external Flash, the program runtime will increase significantly. In the interval between two calls to the UART.any () method to obtain the serial port status, it is very likely that the gyroscope has already sent a large amount of data to the serial port, causing the serial port's FIFO memory to overflow.In this case, we need an interrupt. The function of the so-called interrupt is that once there is receivable data on the serial port peripheral, the preset interrupt callback function will be called to receive the data and perform corresponding processing.

Let's take another example where we previously used GPIO to read the press of an external key. The difference between the external interrupt method and the polling method is shown in the following figure:

Diagram: 06 Interrupt —— First Draft of Document Tutorial

Extending the above example, we can obtain two different program execution modes: polling and interrupt.

Simply put, an interrupt is the core mechanism for an MCU to handle "sudden tasks" — for example, when a timer expires, data is received via a serial port, or a sensor triggers a signal, the MCU cannot wait until the core "finishes its current work" to process these events; instead, an interrupt will "interrupt" the core's ongoing operation to prioritize the urgent task. The NVIC (Nested Vectored Interrupt Controller) acts as the "interrupt scheduler" for each core, responsible for managing interrupt priorities and execution sequences.

1.2 Types of Interrupts

Interrupts can originate from inside the MCU or from external devices of the MCU. Simply put, they can be categorized into GPIO external interrupts, peripheral interrupts, and core interrupts:

IRQ and Priority

  • IRQ: short for "Interrupt Request", is an "urgent call signal" sent by peripherals (such as timers and UARTs) to the processor core. When a peripheral needs the core to process a task immediately (for example, when a timer expires or data is received via a serial port), it triggers the corresponding IRQ, prompting the core to suspend its current work and prioritize handling this urgent task.
  • Priority: refers to the sorting rule for the urgency of interrupt tasks. A chip may receive multiple IRQs at the same time, and tasks with higher priority will be processed first by the core to prevent urgent tasks from being delayed.

1.3 NVIC Nested Vectored Interrupt Controller

The main function of the NVIC (Nested Vectored Interrupt Controller) is to process interrupts, and it is responsible for managing the priority and execution sequence of interrupts:

The NVIC contains an interrupt vector table, which serves as the "core navigation tool" for the CPU to process interrupts. Simply put, the interrupt vector table is a table arranged in ascending order of interrupt type numbers, where each entry corresponds to an interrupt type and stores the interrupt vector and the address of the corresponding Interrupt Service Routine (ISR) for that interrupt:

The "nesting" feature of the NVIC is one of its core characteristics and the key that distinguishes it from ordinary interrupt controllers. The so-called "nesting" means that the NVIC allows users to set a priority level for each type of interrupt:

  1. When the CPU is handling a low-priority interrupt, if an interrupt request with a higher priority arrives at this moment, the NVIC will allow the higher-priority interrupt to "preempt" the control of the CPU, that is, suspend the processing of the current low-priority interrupt and prioritize the execution of the service routine for the higher-priority interrupt;
  2. After the higher-priority interrupt processing is completed, the CPU returns to the previously suspended low-priority interrupt and continues to finish the remaining processing tasks.

This process is called interrupt nesting. This mechanism ensures that the most urgent events in the system (such as hardware failures and important data reception) can be processed with priority, preventing urgent events from being delayed due to low-priority events occupying the CPU.

In addition, the NVIC also has the function of interrupt masking (disabling): it records which interrupts are set to the "masked state" by the user, and for these masked interrupts, the NVIC will directly ignore their requests and not pass them to the CPU. This is just like the front desk can refuse to receive customers on the blocklist, ensuring that the CPU will not be disturbed by unnecessary interrupts.

When an interrupt request is generated and scheduled by the NVIC, the CPU processes the interrupt in accordance with fixed steps. The entire process is analogous to a scenario where you are in the middle of writing a document when you suddenly receive an urgent email notification, and after handling the email, you return to the document to continue writing:

Diagram: 06 Interrupt —— First Draft of Document Tutorial

The fixed process is as follows:

  1. Normal program execution: The CPU originally executes the user's main program in sequence, and after completing each instruction, it actively checks whether the NVIC has any interrupt requests that need to be processed;
  2. Suspend the current program: When the CPU detects the interrupt signal transmitted by the NVIC, it will immediately stop executing the current main program;
  3. Save the program state: The CPU will automatically save key information such as the execution progress of the current main program and register data to ensure that it can accurately return to the interrupted position and continue execution subsequently;
  4. Find and execute the interrupt service routine: The CPU queries the interrupt vector table according to the type number of the interrupt signal, locates the address of the corresponding interrupt service routine, and then loads and executes this handler;
  5. Restore program state: After the execution of the interrupt service routine is completed, the CPU will automatically restore the previously saved state of the main program;
  6. Resume execution of the main program: The CPU returns to the point where it was interrupted and continues to execute the original main program.

After this processing is completed, the CPU automatically restores the saved information and resumes executing the program from where it stopped.

The following figure shows the state transition diagram when a user program switches to an interrupt service routine:

Diagram: 06 Interrupt —— First Draft of Document Tutorial

2 NVIC Interrupt Controller on Raspberry Pi Pico

2.1 Interrupt

Each core (Core0 and Core1) has an independent NVIC, which acts as a dedicated "interrupt dispatcher". It can receive 32 interrupt signals, but the RP2040 only uses the first 26 of them (IRQ0 to IRQ25), while the remaining IRQ26 to IRQ31 are reserved (they can also be forcibly triggered). When a peripheral (such as a timer or UART) triggers an urgent task, it sends a signal to the corresponding IRQ, and the NVIC then schedules the core to process it.

On the RP2040, only the lower 26 IRQ signals are connected to the NVIC, while IRQs 26 to 31 are not tied to any source. By writing to bits 26 to 31 in the NVIC ISPR register, the core can still be forced to enter the corresponding interrupt handler.

The interrupt vector table of the RP2040 is as follows. This table acts as a "task list for IRQs", where each IRQ number corresponds to a specific "source of urgent tasks":

RP2040 IRQ0 0 IRQ20 UART0 26 31

For example, IRQ0 corresponds to "IRQ of Timer 0"(meaning Timer 0 has timed out), and IRQ20 corresponds to "IRQ of UART0"(meaning UART0 has received data). Once the core sees the IRQ number, it can immediately identify which peripheral sent the "urgent call" and then invoke the corresponding handler.

The meanings of each interrupt are as follows:

Interrupt nameInterrupt Meaning and Additional Notes
TIMER_IRQ_x (x=0~3)Interrupts related to the general-purpose timers (x is 0-3, corresponding to the interrupts of the 4 general-purpose timers)
PWM_IRQ_WRAPPWM timer wrap interrupt (triggered when the PWM counter reaches its maximum value and wraps around)
USBCTRL_IRQUSB control interrupts (triggered by events such as USB peripheral state changes and data transfers)
XIP_IRQInterrupt related to the SSI synchronous serial interface controller; the signal comes from the SSI controller of the XIP cache for external flash, and can be used in configurations where code runs from SRAM instead of flash; once enabled, the XIP block can be used as a normal SSI peripheral
PIOx_IRQ_y (x=0/1, y=0/1)Programmable IO interrupts (x is 0-1 for the 2 PIO blocks, y is 0-1 for the 2 interrupts of each PIO block)
DMA_IRQ_x (x=0/1)DMA controller interrupts (x is 0-1 for the interrupts of the 2 DMA controllers)
IO_IRQ_BANK0General-purpose GPIO interrupts (triggered by level changes on the Pico's ordinary GPIO pins)
IO_IRQ_QSPIInterrupts related to the QSPI peripheral GPIOs connected to external flash (triggered by events on the QSPI interface GPIO pins)
SIO_IRQ_PROCx (x=0/1)Single-cycle low-latency IO interrupts (x is 0-1 for the SIO interrupts of the 2 CPU cores)
CLOCKS_IRQClock system interrupts (triggered by events such as clock module state changes and frequency adjustments)
SPIx_IRQ (x=0/1)SPI peripheral interrupts (x is 0-1 for the interrupts of the 2 SPI peripherals, such as receive complete and transmit complete)
UARTx_IRQSerial port interrupts (interrupts of the UART peripheral, such as receive complete, transmit complete, and communication errors)
ADC_IRQ_FIFOInterrupts related to the FIFO memory of the ADC analog-to-digital converter (triggered by events such as the ADC FIFO buffer reaching a threshold or overflowing)
I2Cx_IRQ (x=0/1)I2C serial communication bus interrupts (x is 0-1 for the interrupts of the 2 I2C peripherals, such as receive complete and transmit complete)
RTC_IRQRTC real-time clock interrupts (triggered by RTC timing events, alarms, etc.)

Actually, interrupts can be further divided into the following two types: maskable interrupts (IRQ, Interrupt Request) and non-maskable interrupts (NMI, Non Maskable Interrupt), the core difference between which lies in "whether they can be selectively ignored by the CPU", as summarized in the table below:

FeatureMaskable Interrupt (IRQ)Non-Maskable Interrupt (NMI)
Core DefinitionAn interrupt that can be selectively ignored through software configuration (masking)The highest-priority interrupt, which breaks through normal masking restrictions
MaskabilityCan be completely masked by the CPU's interrupt mask bit; once masked, the CPU will not respond even if the interrupt occursCannot be masked by normal means (the core meaning of the name); can only be configured in a limited way through dedicated registers
Trigger ScenariosRoutine peripheral events (such as UART data reception, GPIO button presses, timer timeouts)Severe emergency events (such as hardware faults, power loss, coprocessor errors, core hardware exceptions)
PriorityLower; multiple IRQs can be nested by setting priorities through the NVICHighest; can interrupt an IRQ being handled, and even the CPU's normal operation

Simply put:

The 26 system interrupts of the Raspberry Pi Pico (such as TIMER_IRQ, UART_IRQ, GPIO_IRQ, etc.) will undergo two-step processing before being merged with kernel interrupts into a single NMI signal that is fed into the corresponding CPU core; the entire process can be understood as "interrupt filtering and merging":

  1. Step 1: Masking (selectively ignoring some system interrupts): First, 26 system interrupts go through masking processing — this is equivalent to setting a "do not disturb switch" for these interrupts. You can configure the mask register to select "which system interrupts to temporarily ignore even if they occur". For example, you can set "mask UART_IRQ", then even if the UART receives data, this interrupt will not enter the subsequent processing flow.
  2. Step 2: Perform an OR operation with the kernel interrupt to merge them into an NMI: After being masked, the remaining "non-ignored system interrupts" will undergo an OR operation with the CPU's internal kernel interrupts (such as more severe internal exceptions like power loss, coprocessor operation errors, and hardware faults) — if any one of these interrupts occurs, the result will be "interrupt present". Eventually, these scattered interrupt signals will be merged into a unified NMI signal and fed into the CPU core.

The core objective of this process is to: uniformly encapsulate all urgent events requiring the highest priority processing into NMI signals, so as to ensure that the CPU can respond to these critical events first.

NMIs are not absolutely unmaskable

Many beginners mistakenly assume that NMI stands for "interrupts that absolutely cannot be masked", but in reality, the true meaning of "Non-maskable" is that even when normal maskable interrupts (IRQs) are disabled, such NMI interrupts can still be delivered to the CPU.

In other words, the "non-maskable" property of NMI is relative to the masking of regular interrupts, and it is not absolutely impossible to configure: we can still perform limited configuration on the enablement of NMI signals through dedicated registers (this is a special configuration for NMI, which is different from regular interrupt masking).

The Raspberry Pi Pico provides dedicated configuration registers for the two CPU cores (Core0, Core1) respectively. These registers belong to the Syscfg register block (base address: 0x40000000) and are used to control the enabling of NMI signals:

The core function of these two registers is to precisely control which merged NMI signals can actually be delivered to the corresponding core. For example, you can use the PROC0_NMI_MASK register to configure that "only NMI signals related to hardware faults are delivered to Core0, while other NMI signals are temporarily masked". This is a special configuration for NMIs and the only way to "filter" NMIs.

06 Interrupt —— First Draft of Document Tutorial

The bits [31:0](32 bits in total) of the two registers correspond one-to-one to the 32 system IRQs (interrupts) of the Raspberry Pi Pico:

Its operating characteristics include:

2.2 NVIC Controller

The base address of the registers related to the NVIC interrupt vector controller is PPB_BASE= 0xe0000000, which is a register set in the Raspberry Pi Pico that controls "internal peripherals that directly interact with the core". These internal peripherals (such as the SysTick timer and NVIC interrupt controller) are core components tightly coupled with the CPU core, and are responsible for basic functions such as core timing, interrupt scheduling, and memory protection.

Special attention: All registers under PPB_BASE can only be read and written in "word (32-bit)" mode (byte/half-word operations are not allowed), and are stored in "little-endian" format (i. e., the lower byte of the data is stored at the lower memory address).

2

Wherein:

The NVIC of Raspberry Pi Pico interrupts supports nested interrupts in hardware: a low-priority interrupt can be preempted by a high-priority interrupt (or another exception such as a hard fault), and the low-priority interrupt will resume once the high-priority exception is completed.

When multiple IRQs are triggered simultaneously, the core processes them in sequence according to their "urgency level". The NVIC priority level of the RP2040 is defined by 2 bits, which corresponds to 4 types of NVIC interrupt configurations, and the priority is judged in two layers:

06 Interrupt —— First Draft of Document Tutorial

You can use the NVIC_IPRx Register (x = 0 to 7) to set a priority level ranging from 0 to 3 for each interrupt, where 0 represents the highest priority and 3 represents the lowest priority.

M0PLUS NVIC_IPR0 0xe400 0 3 1 31-30 29-24 23-22 2

We can use the NVIC_ISER register to enable interrupts or check whether an interrupt is enabled. If an interrupt that is currently pending (i. e., a low-priority interrupt that has been preempted by a higher-priority interrupt) is enabled, the NVIC controller will activate the interrupt according to its priority. If an interrupt is not enabled, asserting its interrupt signal will set the interrupt to the pending state, but the NVIC will not activate the interrupt regardless of its priority.

M0PLUS 0xe100 0 1

Similarly, we can disable interrupts or check whether an interrupt is disabled by means of the NVIC_ICER register.

06 Interrupt —— First Draft of Document Tutorial

We can use the NVIC_ISPR register to force an interrupt into a pending state or check whether an interrupt is pending.

06 Interrupt —— First Draft of Document Tutorial

Similarly, we can use the NVIC_ICPR register to clear the pending status of an interrupt or check whether an interrupt is pending.

M0PLUS 0xe280 31 0 0x00000000 1

3. Software Control Method

3.1 Peripherals with Interrupt Function

In previous versions of MicroPython for the Raspberry Pi Pico (taking v1.23.0 as an example), only the following peripherals support interrupt functionality:

Peripheral

Description of the interrupt method

Pin Class

External level changes can trigger GPIO external interrupts, and the interrupt callback function will be called once the interrupt is triggered.

I2S Digital Audio Interface Category

An interrupt is triggered when the buffer (buf) object is filled or emptied, and the interrupt callback function is called after the interrupt is triggered.

Real-Time Clock (RTC) Class

When the timer reaches the set time, an interrupt is triggered, and the interrupt callback function is called after the interrupt is triggered.

Timer Class

Regularly execute the interrupt callback function; the system/hardware timer can be configured for periodic or one-shot callbacks (similar to a timed interrupt),

Suitable for periodic tasks or timeout processing.

Direct Memory Access (DMA) Class

An interrupt is triggered when DMA data transfer completes or a null trigger is received, and the interrupt callback function is invoked after the interrupt is triggered.

finite-state machine StateMachine class

Interrupts related to the finite-state machine can be triggered by a digital bit of 0 or 1, and an interrupt callback function will be called once the interrupt is triggered.

It can be seen that MicroPython's SDK does not provide interrupt functions for other peripherals, such as interrupt reception for serial ports, but this does not mean that we cannot use other methods to replace polling (using while loop to call UART.any () to check whether there is data available for reception on the serial port). We can use methods such as timer-based regular serial port status query, multi-threading, and coroutines to complete the timely reception of serial port data more efficiently and accurately.

In the latest version of MicroPython for Raspberry Pi Pico (taking v1.26.0 as an example), interrupts for the newly added I2CTarget class and UART class are shown in the table below:

Peripheral

Description of the interrupt method

I2CTarget Class

You can configure a Pico (or other board) as an I²C slave (target), and register IRQ callbacks for a variety of events, including address matching, read/write requests, read/write completion, etc. Some events require the use of hard IRQ (set hard= True when real-time performance is critical).

UART class

Interrupt triggering has been implemented on multiple ports (including rp2), and the supported trigger types include IRQ_RXIDLE, IRQ_RX, IRQ_TXIDLE, IRQ_BREAK, etc. (there may be differences depending on the port; rp2 supports RX, RXIDLE, TXIDLE, etc.).

UART.irq () is the core method for configuring serial port interrupts on the Pico, which is used to bind an interrupt handling function to a specified UART instance (such as UART0/UART1). When a preset event (e. g., a character is received, the receive line is idle) occurs on the serial port, this function will be automatically executed, eliminating the need for the main program to perform polling on the serial port status and greatly improving the response efficiency of the serial port.

The official UART interrupt method is shown below:

06 Interrupt —— First Draft of Document Tutorial
esp32 rp2 stm32 rp2040 cc3200
ParameterMeaning and Pico-specific notesAdditional notes
handlerOptional, interrupt handler function (takes only 1 argument, the UART instance that triggered the interrupt, such as UART0); set to None to disable the interrupt.
⚠️ Pico note:
1. When hard=True, the function must not allocate memory (such as print(), creating lists / string concatenation), otherwise the system crashes;
2. hard=False (default) is less restrictive, but it is recommended that the function only perform core operations (such as caching data).
triggerInterrupt trigger conditions (multiple conditions can be combined via ``), trigger sources and characteristics supported by Pico (RP2):
1. UART.IRQ_RXIDLE: triggers when the RX line is idle after receiving ≥1 character (suitable for processing complete data segments);
2. UART.IRQ_TXIDLE: triggers only when the sent message is longer than 5 characters, and 5 characters are still waiting to be sent when it triggers;
3. UART.IRQ_BREAK`: triggers when a Break state is detected on the RX line; after triggering, a valid character must be received before it can trigger again.
hardInterrupt type: - False (default): soft interrupt (handled by the virtual machine, slightly higher latency, fewer restrictions); - True: hardware interrupt (driven directly by RP2040 hardware, extremely low latency, strict restrictions). ⚠️ Pico fully supports this parameter (unlike ESP32).

For the RP2040 corresponding to the Raspberry Pi Pico (the "RP2" row in the table), the UART interrupt trigger sources it supports are as follows:

CC3200 ESP32 RP2 STM32

4. Application Experiment

4.1 Serial Port Interrupt Case

4.1.1 Preparations before the experiment

In the following experiment, we need to use the MiniUSB data cable to connect the Fengya No. 1 Board - Universal Compatible Expansion Board 's UART0 USB port to the USB port on the computer:

4.1.2 Receive Idle Interrupt (IRQ_RXIDLE): Receive Complete Data Frame

The UART receive idle interrupt (IRQ_RXIDLE) is a core interrupt mechanism for serial communication in MicroPython / embedded development. In simple terms: when the UART receive pin (RX) transitions from the busy state of "continuous data transmission" to the idle state of "no new bytes received within the specified duration", this interrupt will be triggered.Its core value lies in accurately identifying the completion of receiving "a complete frame of data/instructions" — it does not rely on a fixed frame length or end markers (such as \r\n), and only needs a pause (idle state) in data transmission to determine that the reception of one frame of data is completed. It perfectly solves the problem of "how to judge the end of variable-length instruction transmission", and is a common solution for parsing serial port instruction frames in scenarios such as the Internet of Things and industrial control.

Here, we periodically collect simulated temperature and humidity data in the code below, respond to specific commands via the UART idle interrupt and return the corresponding data; after the UART receives a command and triggers the idle interrupt, it parses the command and returns the environmental data (or a prompt for an unknown command), then resets the buffer.

The complete code is as follows:

# Python env   : MicroPython v1.27.0
# -*- coding: utf-8 -*-        
# @Time    : 2025/12/28 10:37 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : Serial receive idle interrupt (IRQ_RXIDLE): receive a complete command and return environment data

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

# Import MicroPython standard library modules
from machine import Pin, UART
# Import the time module
import time
# Used to simulate environment sensor data
import random

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

# Environment data cache (temperature + humidity)
env_data_cache = {"temp": 0.0, "humi": 0.0}
# Serial receive buffer (pre-allocated 128 bytes)
rx_buffer = bytearray(128)
# Buffer index
buf_index = 0

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

def uart_rxidle_handler(uart: UART) -> None:
    """
    Serial receive idle interrupt handler: reads a complete command and returns environment data.

    Args:
        uart (UART): The UART instance that triggered the interrupt (machine.UART type).

    Notes:
        - When the interrupt fires, read all unprocessed characters into the buffer to avoid data loss.
        - The maximum buffer length is limited to 64 bytes to prevent index overflow from causing program errors.
        - Only UTF-8 encoded commands can be parsed; non-UTF-8 characters may cause decoding to fail.
        - Recognizes the "GET_ENV_DATA" command and returns temperature and humidity data; other commands return an unknown-command message.
        - Reset the buffer index immediately after the command is parsed, so the next reception is not affected.
    """
    global buf_index, env_data_cache

    # Read all unprocessed characters into the buffer
    while uart.any() and buf_index < len(rx_buffer):
        rx_buffer[buf_index] = uart.read(1)[0]
        buf_index += 1

    # Parse the complete command
    if buf_index > 0:
        cmd = bytes(rx_buffer[:buf_index]).decode('utf-8').strip()
        # Respond to the environment data query command
        if cmd == "GET_ENV_DATA":
            resp = f"Env Data - Temp: {env_data_cache['temp']}C, Humidity: {env_data_cache['humi']}%\r\n"
            uart.write(resp)
        else:
            uart.write(f"Unknown command: {cmd}\r\n")
        # Reset the buffer
        buf_index = 0

def collect_env_data() -> tuple[float, float]:
    """
    Simulated environment sensor (temperature and humidity) data acquisition function (core business logic of the main task).

    Args:

    Notes:
        - The simulated temperature range is 18.0~35.0℃ and the simulated humidity range is 30.0~80.0%, kept to 2 decimal places.
        - After acquiring data, update the global environment data cache so the latest data is available when the interrupt responds to a command.
        - The return value is a tuple; the first element is the temperature (℃) and the second is the humidity (%).
        - Data acquisition has no hardware dependency and is used only to simulate business logic.
    """
    global env_data_cache

    temp = round(random.uniform(18.0, 35.0), 2)
    humi = round(random.uniform(30.0, 80.0), 2)
    # Update the global cache
    env_data_cache["temp"] = temp
    env_data_cache["humi"] = humi
    return temp, humi

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

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("FreakStudio: Testing UART Recv IRQ_RX")

# Initialize the status LED (onboard Pin25) - indicates the data acquisition status
status_led = Pin(25, Pin.OUT)
status_led.off()

# Initialize UART0: TX=Pin0, RX=Pin1, baud rate 115200
uart0 = UART(0, baudrate=115200, tx=Pin(0), rx=Pin(1))
# Configure the serial interrupt: receive idle trigger (IRQ_RXIDLE), soft interrupt
uart0.irq(handler=uart_rxidle_handler, trigger=UART.IRQ_RXIDLE, hard=False)

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

# Main loop: core business logic (environment data acquisition) + wait for interrupt response
while True:
    # Real business task 1: acquire environment data
    current_temp, current_humi = collect_env_data()
    # Real business task 2: print the acquired data (debugging)
    print(f"Collected - Temp: {current_temp}°C, Humidity: {current_humi}%")
    # LED blinks to indicate the acquisition action
    status_led.on()
    time.sleep(0.1)
    status_led.off()
    # Simulated sensor acquisition interval
    time.sleep(1)

In the code above, we perform the following operations:

  1. Program startup and initialization;
  2. The program enters an infinite loop and repeatedly performs the following operations at a cycle of 1 second:
    1. Call collect_env_data function to simulate environmental data collection: generate temperature data ranging from 18.0℃ to 35.0℃ and humidity data ranging from 30.0% to 80.0%(both retaining 2 decimal places), and update the global env_data_cache cache;
    2. Print the currently collected temperature and humidity data (for debugging use), and control the status LED to turn on for 0.1 second then turn off (to visually indicate the Data Acquisition action);
    3. Delay for 1 second to simulate the actual sampling interval of the sensor, then repeat the above steps.
  3. When the serial port receives a complete command (triggering the "receive idle" interrupt), the main loop is paused and the interrupt processing logic is executed:
    1. Read all unprocessed characters from the serial port and store them in the pre-allocated 128-byte receive buffer (index restriction is applied to prevent out-of-bounds access);
    2. Decode the buffer data into a UTF-8 string, strip the leading and trailing whitespace, and parse the instruction content;
    3. Command Matching: If the command is "GET_ENV_DATA", return the latest temperature and humidity data in the cache via the serial port; for any other command, return the prompt "Unknown command";
    4. Reset the buffer index, the interrupt handling is completed, and the program returns to the main loop to continue executing the Data Acquisition task.

The following is the overall flow chart:

UART0 8

Open the XCOM software and select the COM port corresponding to the CH340K chip:

V2.6 COM3 CH340 CH340K

The serial communication parameters are consistent with those in the program:

115200 1 8

All other sending and receiving parameters can be left as default.

16 0 22 14 57
16 1000

Click to open the serial port:

06 Interrupt —— First Draft of Document Tutorial

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

COM3

As can be seen, the LED on the core board flashes periodically, and the serial command response function also works as expected (sending GET_ENV_DATA returns the corresponding temperature and humidity data, while sending OTHER_COMMAND triggers an "unknown command" prompt), indicating that the overall function operates properly.

4.1.3 Transmit Idle Interrupt (IRQ_TXIDLE): Confirm Completion of Long Data Transmission

The UART transmission idle interrupt (IRQ_TXIDLE) is a core interrupt mechanism for the data transmission link in UART communication. Specifically, it is triggered when the UART transmitter (TX) has completely sent all bytes to be transmitted in the transmit buffer, the transmit buffer is empty, and the TX pin enters the idle state with no data output.Its core value lies in accurately confirming that "the transmission process of a long data block / a complete frame of data has been thoroughly completed", rather than merely triggering the transmission action. It is especially suitable for scenarios that require transmitting large-size data (such as batch sensor logs, long text responses, and binary data streams), and can effectively prevent data loss or disorder caused by modifying the buffer, closing the serial port, or initiating the next transmission before the completion of the current transmission is confirmed.

It corresponds to the receive idle interrupt (IRQ_RXIDLE):

In the following code, we use the IRQ_TXIDLE interrupt flag, which indicates that the long log transmission is nearly complete, combined with the batch caching mechanism to implement reliable serial transmission of simulated sensor logs.

The complete code is as follows:

# Python env   : MicroPython v1.27.0
# -*- coding: utf-8 -*-        
# @Time    : 2025/12/28 11:12 AM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : Serial transmit idle interrupt (IRQ_TXIDLE) - long log transmission status prompt

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

# Import MicroPython standard library modules
from machine import Pin, UART
# Import the time module
import time
# Used to simulate sensor data
import random

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

# Sensor log cache (send after accumulating 6 entries, ensuring length > 5 to trigger TXIDLE)
sensor_logs = []
# Log number
log_seq = 1
# Send state: IDLE (idle) / SENDING (sending)
tx_status = "IDLE"
# TXIDLE interrupt trigger flag
txidle_flag = False

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

def uart_txidle_handler(uart: UART) -> None:
    """
    RP2 serial TXIDLE interrupt handler (soft interrupt); only marks the interrupt trigger state to avoid hardware preemption.

    Args:
        uart (UART): The UART instance that triggered the interrupt (machine.UART type).

    Notes:
        - The RP2 TXIDLE interrupt fires when 5 characters remain to be sent, not when transmission is complete.
        - Mark only in the sending (SENDING) state, to avoid spurious triggers disturbing the state machine.
        - Do not perform UART write operations, to prevent hardware preemption from corrupting data.
    """
    global txidle_flag
    # Mark only while sending
    if tx_status == "SENDING":
        txidle_flag = True

def generate_sensor_log() -> str:
    """
    Generate a fixed-format simulated sensor log, adapted to the RP2 UART buffer characteristics.

    Args:
        None

    Notes:
        - A fixed field format ensures every log entry has the same number of characters, avoiding data truncation caused by length fluctuation.
        - The log number is zero-padded to 4 digits, to prevent visual confusion from the number cycling too quickly.
        - Reset the number when it exceeds 9999, to prevent numeric overflow from affecting log readability.

    Return:
        (str): Simulated sensor log file, fixed format.
    """
    global log_seq

    temp = round(random.uniform(20.0, 40.0), 2)
    pressure = round(random.uniform(950.0, 1050.0), 2)
    # Force a fixed format so every log entry has the same length (avoids truncation)
    log = f"LOG_{log_seq:02d} | Time: {int(time.time())}s | Temp: {temp:5.2f} degC | Pressure: {pressure:6.2f} hPa"
    log_seq += 1
    return log

def send_log_batch(uart: UART) -> None:
    """
    RP2 serial batch send function for 3 log entries, adapted to the hardware FIFO buffer capacity (prevents truncation).

    Args:
        uart (UART): The UART instance used to send logs (machine.UART type).

    Notes:
        - The batch threshold is set to 3 entries, and the total character count fits the RP2 UART FIFO buffer, avoiding data backlog.
        - Use uart.flush() to block and wait, replacing the unreliable uart.txdone(), to ensure sending is complete.
        - Send only in the IDLE state, to avoid multithread-like state races that corrupt data.
        - Write the whole batch of logs at once, to guarantee an atomic send operation at the hardware level.

    Return:
        None
    """
    global sensor_logs, tx_status, txidle_flag

    if len(sensor_logs) >= 3 and tx_status == "IDLE":
        tx_status = "SENDING"

        # Reset the interrupt flag
        txidle_flag = False

        # Concatenate the whole batch of logs (atomic block, sent at once)
        long_log = "\r\n".join(sensor_logs) + "\r\n===== LOG BATCH END =====\r\n"
        print(f"Sending {len(sensor_logs)} logs...")

        # Write the whole batch of logs at once (hardware atomic operation)
        uart.write(long_log)

        # Block until the whole batch of logs is sent
        while uart.flush():
            time.sleep_ms(5)

        # After sending completes, output the TXIDLE prompt to the terminal
        if txidle_flag:
            print("[STATUS] Transmission nearly complete (TXIDLE triggered)")
            txidle_flag = False

        # Clear the cache + restore the state
        sensor_logs.clear()
        tx_status = "IDLE"

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

# Power-on delay of 3 s
time.sleep(3)
# Print debug message
print("FreakStudio: Testing UART Transmit IRQ_TXIDLE")

# Initialize the send status LED (onboard Pin25)
tx_led = Pin(25, Pin.OUT)
tx_led.off()

# Initialize UART0: TX=Pin0, RX=Pin1, baud rate 115200
uart0 = UART(0, baudrate=115200, tx=Pin(0), rx=Pin(1))
# Configure the serial interrupt: transmit idle trigger (IRQ_TXIDLE), soft interrupt
uart0.irq(handler=uart_txidle_handler, trigger=UART.IRQ_TXIDLE, hard=False)

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

while True:
    # Generate logs only when idle (avoids buffer overload)
    if tx_status == "IDLE":
        log = generate_sensor_log()
        sensor_logs.append(log)
        print(f"Generated: {log}")

    # Batch send (blocks until complete)
    send_log_batch(uart0)

    # Update the LED and print the status
    tx_led.value(1 if tx_status != "IDLE" else 0)
    print(f"Transmit Status: {tx_status}")

    # Fixed interval (lower the loop frequency to reduce conflicts)
    time.sleep(2)

In the code above, we have completed the following tasks:

  1. Program startup and initialization;
  2. The program enters an infinite loop and repeatedly performs the following operations at a cycle of 2 seconds:
    1. Log generation: This function is called only when the transmission status (tx_status) is IDLE generate_sensor_log to generate a simulated temperature and pressure sensor log in a fixed format (including log ID, timestamp, temperature, and barometric pressure), add the log to the cache list sensor_logs and print the generation information;
    2. Batch sending: call the send_log_batch function. If the number of cached logs ≥ 3 and the system is in IDLE state, execute the batch sending logic:
      • Switch tx_status to SENDING and reset the TXIDLE interrupt flag txidle_flag;
      • Stitch the 3 logs in the cache into a complete long text (with the "LOG BATCH END" end marker), and write and send it all at once via UART0 (to ensure hardware atomic operations and avoid data truncation);
      • Call uart.flush () to block and wait until all data is sent (it checks once every 5ms during this period, replacing the unreliable uart.txdone ());
      • If the TXIDLE interrupt is triggered (txidle_flag is True), print the prompt "Transmission is nearly complete" and reset the flag;
      • Clear the log cache and restore tx_status to IDLE;
    3. Status indication: Control the LED according to tx_status (light up when SENDING, turn off when IDLE), and print the current transmission status;
    4. Delay for 2 seconds: reduce the loop frequency, cut down transmission conflicts, and adapt to the characteristics of the hardware buffer.
  3. TXIDLE Interrupt Response: When the UART0 transmit buffer has 5 remaining characters to be transmitted (a RP2 hardware feature) and triggers the IRQ_TXIDLE interrupt, execute the uart_txidle_handler function: only when tx_status is SENDING, mark txidle_flag as True (only mark the status without performing write operations to avoid data corruption caused by hardware preemption), for the main loop to determine the status that transmission is nearing completion.

The complete flow chart is as follows:

2 3 5

Open the XCOM software and select the COM port corresponding to the CH340K chip:

V2.6 CH340K COM3 CH340

The serial communication parameters are consistent with those in the program:

06 Interrupt —— First Draft of Document Tutorial

All other sending and receiving parameters can be left as default.

16
16 1000ms

Click to open the serial port:

V2.6 CH340KK

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

3

We can see that the running effect of the program fully meets the expectations:

  1. The main loop periodically generates simulated sensor logs in a fixed format (the terminal on the left continuously outputs the log information corresponding to "Generated"), and automatically enters the sending state when the log cache accumulates to 3 entries (the terminal displays "Sending 3 logs");
  2. During the transmission process, the IRQ_TXIDLE interrupt is triggered, and the terminal synchronously prints the callback prompt "Transmission nearly complete"(the callback function for serial port transmission interrupt trigger); meanwhile, the serial port assistant on the right side completely receives the batch log marked with "LOG BATCH END".
  3. The status will be restored to IDLE after the transmission is completed.

The looped and orderly process of log generation - caching - sending not only verifies the marking function of the TXIDLE interrupt for long data sending status, but also ensures reliable serial port transmission of batch logs.

When using MicroPython 's UART to send idle interrupts ( IRQ_TXIDLE ) on the RP2 platform, the core attention is to strictly control the total number of characters sent in a single batch to adapt to the limited capacity of the RP2 UART hardware send buffer (FIFO):

References

https://micropython.org.cn/forum/viewtopic.php?t=1230

https://github.com/micropython-Chinese-Community/mpy-lib/tree/master/misc/irqUART

https://www.cnblogs.com/wudibuzaijia/p/8556572.html

https://gitee.com/shaoziyang/projects

https://www.skyone.host/2021/05/13/micropython-you-ya-de-shi-xian-zhong-duan/

https://forum.micropython.org/viewtopic.php?t=1448

Version Record

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/17

Initialize the document, based on v1.23.0 version of MicroPython.

However, in the software control method, descriptions for the following have been added in v1.26.0: I2CTarget class and UART class interrupts.

v1.0.1

Li Zisheng

2025/12/05

Some of the images have been replaced.

v1.0.2

Li Zisheng

2025/12/21

Optimize the document, a serial port interrupt case is to be added.

v1.1.0

Li Zisheng

2025/12/27

Added a serial port interrupt example, based on v1.27.0 version of MicroPython.