Labs / MicroPython tutorials

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

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

Contents

1. Hardware Explanation

1.1 Basics of USB (Universal Serial Bus)

Here, since the USB protocol is rather complex and covers a wide range of knowledge points, we will only explain the basic knowledge of the USB protocol to help you quickly form a general and macroscopic understanding of the USB (Universal Serial Bus).

1.1.1 Introduction to USB (Universal Serial Bus)

USB (Universal Serial Bus) is a widely adopted universal serial bus standard that provides a standardized data transmission interface between computer devices and peripherals. It is a Plug and Play bus standard, allowing users to connect and use various peripherals such as mice, keyboards, printers, scanners, etc. on a computer.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy
Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

The USB connection adopts a master-slave architecture, where the host device controls and manages the entire USB system.

As of now, there are a total of four versions of the USB protocol:

The three most common electrical connectors that apply the USB protocol in our daily lives are as follows:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

1.1.2 Development History of USB Protocol

On early PCs, there were serial ports and parallel ports, and even mice, keyboards, and game controllers had dedicated interfaces. Moreover, none of these interfaces supported hot-swapping, meaning devices had to be plugged in before the PC was powered on to function properly. In addition, these various interfaces also consumed valuable CPU resources, such as hardware interrupts and DMA channels.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
In the early 1990s, apart from the serial COM port, the PS2 keyboard/mouse port and the RS232 port (at that time, only high-end motherboards came with these three ports), most other modules had to connect through the PCI, AGP and ISA parallel interfaces, such as common graphics cards, sound cards, network cards, video decoder cards and LPT printer ports. Many low-end computers, because of weak CPU floating-point performance, even needed an external "coprocessor" to get a graphical interface (for example, an 80386 paired with an 80387 coprocessor).
12 USB Universal Serial Bus - Document Tutorial First Draft Copy
Before USB appeared, data was mainly transferred over the parallel port.

To address these issues, Ajay Bhatt put forward the concept of the Universal Serial Bus, namely USB. One of the core design philosophies of USB is to provide a unified solution for the various interfaces on PCs while replacing the numerous and diverse interfaces and slots on computer motherboards.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
Ajay Bhatt, the father of USB, in a portrait photo

Ajay Bhatt and his team worked on joint R&D at Intel alongside six other companies including IBM, Microsoft, DEC, NEC, Compaq and Nortel. Eventually in 1995, the first USB-supporting integrated circuit was manufactured by Intel, and the first commercially available USB 1.0 RRC standard was released in November 1995. At the same time, the seven companies jointly founded the non-profit organization USB-IF (USB Implementers Forum).Prior to this, USB 0.8, USB 0.9 and USB 0.99 were released as "pre-release versions" that same year, but had not yet been put into commercial use.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
USB logo from the USB-IF

USB 1.0 offers two communication rate modes:

USB 1.0 supports Self-Adaptation configuration, which can automatically adapt to peripheral devices without users changing device settings. This interface also supports hot-swapping, so devices can be replaced without restarting the host. Although it was the first commercial version of USB, it was not widely accepted by the market, and there were very few devices available for consumers.

Interestingly, although Intel was the first company to invest in USB technology, the world's first product to adopt USB technology was not developed by Intel (but the world's first USB-compatible integrated circuit was manufactured by Intel, so please note the distinction!). The world's first product to feature USB technology was Apple's iMac G3, released in 1998, which conformed to the USB 1.1 standard established that same year.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

As the market demands higher compatibility for PCs and their various peripherals, and applications become increasingly complex, the requirements for data transfer rates have gradually risen. USB 2.0 was released in April 2000; in addition to being compatible with USB 1.x full-speed signal transmission, it also added an operating mode that supports a higher maximum signal transmission rate of 480 Mbit/s, which is referred to as High Speed.USB 2.0 also provides Plug and Play functionality for multimedia and storage devices, and supports power supply via USB connectors with ratings up to 5 V and 500 mA.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

To meet the growing demand for communication rates, the USB Implementers Forum (USB-IF) introduced the USB 3.0 standard in 2008, which supports a data rate of up to 5 Gbit/s and is referred to as the SuperSpeed mode. Subsequent iterations include the SuperSpeed+ mode and SuperSpeed++ mode, which offer theoretical maximum data rates of 10 Gbit/s and 20 Gbit/s respectively.

For the communication rates and feature changes of various USB versions, please refer to the table below:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

1.1.3 Overview of USB System

The USB system is a master-slave communication system with a "tiered star topology" structure, which consists of one host and up to 127 peripherals (also referred to as Devices or Peripherals).

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Peripherals fall into two categories: functional peripherals (Functions) and hubs (HUBs):

By cascading hubs (connecting a hub to another hub), you can expand the number of peripherals that can be connected, ultimately forming a pyramid structure as shown in the left figure. At the top of the pyramid are the host and the root hub, which can be connected to functional peripherals or other hubs. Extending downward layer by layer, this forms a hierarchical star connection topology, which is the so-called "Tiered star topology". The protocol specifies a maximum of 7 network layers, which corresponds to the cascading of up to 5 hubs.

USB adopts a polling broadcast mechanism for data transmission, all transfers are initiated by the host, and only one data packet is allowed to be transmitted at the same time. Devices are distinguished by 7-bit bus addresses, among which address 0 is reserved and unavailable to users for devices without assigned addresses, so a host can support up to 127 devices.

After a peripheral is connected to the bus, it must first undergo an enumeration operation before it can be used. On the one hand, the enumeration operation is to assign an address as mentioned above; on the other hand, it obtains the device descriptor to confirm information such as the device type and manufacturer, so that the host can select the corresponding driver. In the USB protocol, functional devices are further subdivided according to their different functions, such as HID, CDC, etc. , which will be described in detail in subsequent introductions.

We have already mentioned that all communications over USB are initiated by the host. This means that no two devices can communicate directly with each other. Even if a device has data to send to the host, it must wait for the host's command. However, there is an exception: when a device is placed in the "Suspend" state by the host, the device can send a "remote wakeup" signal to the bus.

Early USB systems were generally used for peripheral expansion of PCs, so the host was usually a PC, and any device connected to a PC was a peripheral. With the rise of smart devices, or handheld devices as they are also called, a demand has emerged that such devices should be able to connect to a PC as a peripheral and also expand via the USB system as a host. This gave rise to the so-called OTG (On The Go) devices, which have made some adjustments in physical wiring and Communication Protocol, enabling the device to switch between host and slave roles.

Generally speaking, USB interfaces are very convenient to use, as they provide a unified interface for various peripheral devices. However, due to their versatility, the corresponding protocols are relatively complex and involve a wide range of aspects. A brief introduction to each aspect is given below.

1.1.4 USB Physical Interface

Since USB is a master-slave architecture system, it always establishes a connection between a host and a peripheral. To prevent incorrect cabling, the connectors at the two ends of a USB cable are necessarily different. The connector plugged into the host side is generally referred to as a Type-A connector, while the one on the peripheral side is a Type-B connector.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

The figure below lists some common USB connectors.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Standard USB 2.0 ports and cables all feature a 4-wire design: VBUS and GND serve as the power line and ground line respectively, used to supply power to certain USB devices. VBUS typically provides a voltage of 5V, while D+ and D- form a pair of differential twisted pairs for data transmission – this is somewhat similar to the RS-485 serial port we mentioned in serial communication, except that the voltage levels on the lines differ. The advantage of using differential signals is that these signals are less susceptible to electromagnetic interference from surrounding devices.They also do not emit any electromagnetic radiation that could interfere with nearby electronic devices, which is particularly important as the USB protocol is designed to operate around sensitive components such as microprocessors and microcontrollers.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Later, for USB OTG devices, Mini connectors and Micro connectors were introduced, with cables and connectors evolving from the original four-wire configuration to a five-wire setup. The additional wire is labeled as the ID signal line, which is used to distinguish the identity of the device:

A USB host can supply power to a device via the VBUS line on the cable, and devices can be categorized into the following two types according to whether they require current supply from the host:

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

It should be noted that the device cannot supply power to the host, which means that the VBUS line of the device cannot sink current to the bus.

USB is a communication bus that supports hot-plugging. In the USB protocol, the Host can determine whether a device is plugged in by detecting the level changes of the D+ and D- lines: After a USB device is connected, it will pull the two signal lines D+ and D- to a specific level combination; the host will monitor the level states of the D+ and D- lines, and identify the type of the connected device according to different level combinations.

Let's take a look at a common circuit diagram for the connection between a host and a device:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

It can be seen that on the ports of the host or hub, the D+ and D- differential signal lines are both pulled down to ground via a 1.5K resistor.

For USB devices, there are two scenarios:

When a device is plugged into a port, the voltage level on the signal line connected to the pull-up resistor is divided by the pull-up and pull-down resistors, which appears as a high-level signal to the connector. The hub then detects that a device has been inserted, and reports this signal to the host either directly or via an upstream hub. The host then determines the communication speed of the newly inserted device based on the voltage level on the D+ or D- line.

For high-speed devices, the host will first identify them as full-speed devices by default, and then switch them to the high-speed mode through further data interaction with the devices.

1.1.5 USB Communication Hierarchy

The USB protocol consists of multiple layers, mainly including the following layers:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

From the bottom layer to the top layer, they are as follows:

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

These three layers have a clear division of labor and together form a complete USB communication system:

This layered design endows the USB system with excellent scalability and portability: new devices only need to be developed at the application layer, without the need to modify the underlying physical and logic implementations.

USB PHY Chip

USB Phy chip is a dedicated integrated circuit chip that implements the functions of the USB physical layer, and it mainly includes the following functions:

  1. Electrical interface: Provides the electrical characteristics required by physical layer specifications such as voltage, current and impedance for USB data cables.
  2. Signal encoding/decoding: Encode the digital data sent by the host or device into analog signals that comply with the USB physical layer standards, and decode and restore the digital data at the receiving end.
  3. Clock Recovery and Synchronization: Recover the clock signal from the received data stream to ensure that the transmitter and the receiver remain synchronized.
  4. Differential signal transmission: Data is transmitted using differential signal technology to suppress common-mode interference and improve anti-interference capability.
  5. Hot-swap support: Provides hot-swap detection and connection functions, and supports Plug and Play for devices.
  6. Power management: controls the power supply of USB devices, including overcurrent protection, short-circuit protection, etc.

USB Phy chip is a core component for physical layer communication between USB devices and hosts. It implements all physical layer requirements specified in the USB standards, ensuring the reliable operation of the entire USB system. Major suppliers of mainstream USB Phy chips include Microchip, Texas Instruments, and Cypress.

1.1.6 USB Communication Endpoints and Endpoint Descriptors

An endpoint is the most basic unit for communication between a USB device and the host. Logically, each USB device consists of multiple independent endpoints:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Endpoints in the USB protocol support four transfer modes:

It should be noted that every USB device has a set of default endpoints operating in control transfer mode, which are used to transmit configuration and control information. These are the OUT and IN endpoints with endpoint number 0. When a USB device is first plugged in and has not yet been assigned an address, the host can only access endpoint 0 via bus address 0. At this point, the communication capability of the USB device is limited; only after the host obtains the device descriptor through endpoint 0 and completes the enumeration operation can the device communicate with the host normally.

Each endpoint has different operating modes and limitations, and this information needs to be notified to the host during the device enumeration process. The descriptor that describes the operating modes and limitations of an endpoint is called an Endpoint Descriptor, which records the following key information about the endpoint:

Through endpoint descriptors, the host can learn the specific characteristics of each endpoint, so as to correctly communicate and exchange data with them.

1.1.7 USB Enumeration Process, Descriptors and USB Device States

When a USB device is plugged into a host, it needs to go through an enumeration process, which mainly includes the following steps:

  1. After detecting the connection of a new USB device, the host will query the basic information of the device, such as the vendor ID, product ID, etc.
  2. The device provides the host with a series of Device Descriptors, which describe its own type, functions, endpoint information and other relevant details.
  3. The host identifies the device type based on these descriptor information and selects the appropriate USB device driver.
  4. The host also assigns addresses to devices and configures them to bring them into working condition.
  5. Finally, the application can access the functions provided by the device by calling the USB driver interface of the operating system.

Every USB device has exactly one Device Descriptor, which defines information such as the USB version number used by the device, the device class code, device subclass code, protocol code, vendor information, and the number of possible configurations. A USB device can have multiple configurations, but only one can be active at a time.

Each configuration of a USB device corresponds to a Configuration Descriptor, which defines information such as the device's power supply mode and the number of supported interfaces. A USB device can support multiple interfaces, and USB devices with multiple interfaces can be divided into two types:

Taking the common USB composite device, the USB audio device, as an example, it usually includes the following interfaces:

In USB devices, the Interface Descriptor is used to describe interface information, which includes the following types:

It should be noted that one interface may involve multiple endpoints, and each endpoint has one endpoint descriptor.

As we mentioned above regarding the types and subtypes of interfaces, in fact, to facilitate the management and access of different types of USB devices, the USB protocol defines a series of device classes and subclasses, and the main types of USB devices are as follows:

The classification of these classes is reflected in the class, subclass and protocol-related fields of the device descriptor and interface descriptor, mainly the interface descriptor:

The host selects a driver based on the information of these device types and the vendor information mentioned in the device descriptor.

The USB protocol specifies that USB devices have six operating states:

These state transition processes correspond to the enumeration process of the USB device, and the host will perform corresponding operations and configurations according to the current state of the device until the device is fully initialized and ready.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

It should be noted that if the device loses connection with the host in any state, it will return to the Detached state. This state transition mechanism ensures that USB devices can be safely plugged, unplugged and managed.

When we plug a USB device into an available port on a PC, the PC needs to go through a series of operations to assign an address to the device, negotiate and select the appropriate device driver, and perform necessary configuration for the USB device. This process is what we refer to as the enumeration process, the details of which are as follows:

  1. Device Connection Detection
    • Due to the hot-swap design of USB connectors, inserting a USB device into a port of the HUB will change the connection status of the HUB.
    • When the host queries the HUB, the status notification sent by the HUB indicates that the device has been connected.
    • At this point, the host becomes aware of the port where the newly inserted device is located
  2. Port Reset
    • The host shall wait for at least 100ms until the device is fully inserted and the power supply becomes stable
    • The host sends commands to the HUB to enable and reset the ports, putting the device into the Default state.
    • The device draws no more than 100 mA from the VBUS pin to complete basic function configuration.
    • The host can access the device via the default address 0
  3. Get Device Descriptor
    • The host communicates with endpoint 0 of the device by accessing the device via address 0
    • Get device descriptor information
  4. Select Configuration
    • The host selects an appropriate configuration based on the device descriptor information
  5. Assign Address
    • The host assigns a unique device address to the device.
  6. Load the driver
    • The host selects and loads the appropriate USB driver based on the device information.
    • The device enters the Configured state
  7. Set up interface
    • The host initializes and configures each interface of the device.
  8. Device ready
    • So far, the enumeration process of the USB device is completed, and the device enters the available state.

1.1.8 USB Data Transmission and Data Packets

1.1.8.1 USB Data Transmission

USB is an asynchronous serial communication method (the USB 2.0 protocol adopts half-duplex communication), meaning that only one data packet is transmitted on the bus at any given time. On the USB bus, data is transmitted in little-endian order, that is, the least significant bit is sent first, followed by the most significant bit.

The data signal lines on USB use a pair of differential signals, namely signal D+ and signal D-, which can represent two types of data:

Diff.1 and Diff.0 are the differential signals at the physical layer of USB signals. In terms of the represented data, the data adopts the NRZI (Non-Return-to-Zero Inverted) encoding scheme:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

It should be noted the relationship between differential data and NRZI encoded data: when USB transmits "data 0", the physical layer will generate "diff.0" differential data, but the "diff.0" signal does not necessarily represent "data 0", and it may also be a level transition in NRZI encoding.

If a large number of '1' s are transmitted consecutively on the bus, the level will not transition for a long time, which is detrimental to clock synchronization between the master and slave devices (the USB protocol does not have a separate clock line). Therefore, the USB protocol specifies the following mechanism:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy
  1. Bit Stuffing:
    • When six consecutive "1" s appear on the USB data line, a "0" bit will be forcibly inserted as a synchronization signal.
    • This bit stuffing operation can ensure level transitions, and the receiving end uses this synchronization code to synchronize its own receiving clock to keep it consistent with that of the transmitting end.
  2. Receiver de-stuffing:
    • When the receiving end decodes data, it needs to identify and remove these padded "0" bits.
    • Users do not need to perform this operation, as it is implemented by the chip.
    • the original data sequence can be restored

1.1.8.2 USB Data Packets

On the USB bus, the basic unit of data transmission is the packet, which consists of multiple distinct fields, specifically including:

Any packet starts with a synchronization field and a PID (Packet Identifier), and ends with an EOP (End Of Packet).

These different fields constitute the standard format of USB data packets. According to the different purposes of data packets, the USB protocol defines multiple types of data packets, such as:

The specific data packet specifications are shown in the following table:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Next, we will introduce each data packet one by one.

1. Token Packet

In a USB system, all data transfer transactions are initiated by the host sending a token packet.

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

The token packet consists of the following fields:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Among the four types of token packets listed in the above table, the OUT, IN and SETUP packets share the same data format, while the SOF token packet is slightly different. The CRC5 check for each token packet only verifies the data following the PID field:

2. Data Packet

The structure of the data packet is fixed as: after the sync field and PID, there are N bytes of data, followed finally by a 16-bit CRC16 checksum and the end-of-packet delimiter EOP.

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Wherein, the PID can be DATA0 or DATA1, which are two different types of data packets. This is a mechanism to ensure the reliability of data transmission in high-speed transmission mode, and the USB 1.1 protocol defines exactly these two types of data packets, DATA0 and DATA1:

  1. Alternate use of DATA0 and DATA1:
    • Hosts and devices alternate between these two packet types when transmitting data.
    • help the receiving end identify the sequence of data packets
  2. Fault-tolerant and error-correction mechanism:
    • When the receiving end detects a mismatch in the data packet type, it will consider that an error occurred in the previous transmission.
    • This will trigger the retransmission mechanism and improve the reliability of data transmission.
  3. Data Packet Type Switch:
    • The host and the device each maintain a finite-state machine for packet type switching
    • After successfully transmitting or receiving data, the system will switch to the next packet type

DATA2 and MDATA packets were additionally introduced in USB 2.0, which are applied in high-speed split transactions and high-speed, high-bandwidth synchronous transmissions:

3. Handshake Packet

The handshake packet consists of a synchronization field, a PID, and an EOP, which are used to acknowledge a transmission:

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

Common handshake packet types include the following:

4. Special Packet

Special packages are used for certain special functions, including:

1.1.9 USB Data Frames and Transactions

In USB data transmission, the top-level unit is a data frame, each of which lasts for 1 millisecond. A frame consists of a Start-of-Frame (SOF) data packet and one or more transactions, and the SOF marks the start of a new frame on the USB bus.

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

The basic transmission unit of USB is called a transaction, and a complete transaction consists of the following steps:

  1. Token Phase
    • The host sends a Token Packet to specify the target device and endpoint of this transaction
    • Token packets fall into three types: IN, OUT and SETUP, which are respectively used to indicate the direction and type of data transmission.
  2. Data Phase
    • If there is data to be transmitted, the host or device will send a Data Packet.
    • The size of the data packet is limited by the maximum packet length of the endpoint.
    • Data transmission can be in the IN direction (from the device to the host) or the OUT direction (from the host to the device).
  3. Status Phase
    • The receiver sends a Handshake Packet to indicate the status of data transmission (success/failure)

These three phases constitute a complete USB transaction. The host adopts different transaction types, such as control, bulk, interrupt and isochronous transmission, according to the endpoint type of the device. Based on the device descriptor information, the host reasonably schedules transactions among various devices to avoid conflicts and ensure fairness. This phased transaction mechanism enables the USB protocol to flexibly adapt to the requirements of different types of data transmission and provides an efficient and stable operating environment for devices.

Based on the above, the relationships among Frame, Transaction and Packet are as follows:

Diagram: 12 USB Universal Serial Bus - Document Tutorial First Draft Copy

1.2 Overview of USB Peripherals for Raspberry Pi Pico

The RP2040 chip of the Raspberry Pi Pico integrates a USB 2.0 controller, which can operate in either of the following modes:

The RP2040 chip integrates a USB 1.1 PHY chip internally, and the USB controller is connected to the chip's DP (D+) and DM (D-) pin interfaces via the PHY chip. The hardware of the USB controller implements the functions of the USB physical layer, data link layer and part of the transaction layer, which means that programmers do not need to manually handle the complex details of the USB protocol, but instead focus on the following tasks:

The USB controller features a 4kB DPSRAM, which is used to store the configuration information of the USB device and the data buffer.

USB controllers can operate in two working modes:

The structure of the USB peripheral is as follows:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

It can be seen that USB peripherals are mainly composed of the following parts:

2. Software Control Method

For MicroPython, it divides USB devices into the following two types:

  1. "Runtime" USB Device:
    • Defined after MicroPython startup using the Python API (USBDevice class);
    • It needs to be configured and activated at runtime.
  2. "Built-in" USB devices:
    • Compile into the MicroPython firmware and it will always be available;
    • It usually includes USB-CDC (serial port) and optional USB-MSC (mass storage);
    • Out Of The Box, no additional configuration required.

MicroPython provides the USBDevice class, which is a low-level Python API for implementing USB device drivers:

Unfortunately, according to the answer in the link below, we can see that for the Raspberry Pi Pico, it is not possible to use the USBDevice class to control "Runtime" USB devices as can be done with the PyBoard featuring STM32 chips:

https://github.com/micropython/micropython/issues/6811

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

However, recalling what we introduced about the REPL interactive interpreter, on the Raspberry Pi Pico, the MicroPython firmware comes with a built-in USB-CDC device driver by default, which provides a virtual serial communication channel. This USB-CDC device is a "Built-in" device integrated into the MicroPython firmware and can be used without additional configuration. This means that we can use this virtual serial port together with the system's input and output to complete USB data transmission.

3. Application Examples

3.1 Use the USB-CDC class VCSP virtual serial port to complete data reading and writing

A virtual serial port refers to a USB device that is simulated as a traditional serial port device (COM port), enabling interaction with it using standard serial port Communication Protocol and software. Its main features include:

  1. It provides standard serial port interfaces and functions, such as the configuration of baud rate, data bits, stop bits and other parameters.
  2. It appears as a standard serial port device in the operating system and can be accessed by common serial port applications.
  3. Use CDC (Communication Device Class) USB protocol to convert the data communication of USB devices into standard serial communication
  4. It is usually used in scenarios where compatibility with legacy software or devices is required, such as industrial control systems, testing equipment, etc.

This design of virtual serial port greatly enhances the compatibility and usability of USB devices, allowing even legacy systems to seamlessly connect to new USB devices. The USB driver of the operating system automatically converts USB devices into standard serial port devices, which can be used by upper-layer applications without any modification.

The following code can be found in the elegance-devkit v1\Demo\39 USB_CDC folder of the resource package we provide.

The sample code is as follows:

# Python env   : MicroPython v1.23.0
# -*- coding: utf-8 -*-        
# @Time    : 2024/7/29 1:22 PM
# @Author  : Li Qingshui
# @File    : main.py       
# @Description : USB CDC experiment, using the USB-CDC class built into the MicroPython firmware on the Pico to perform read and write operations

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

import select
import sys
import time

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

# List recording the elapsed times
delta_list = [0] * 10
# Record the number of reads
read_count = 0

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

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

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

# Delay to wait for the device to initialize
time.sleep(3)
# Print debug information
print('FreakStudio : Using USB CDC to read and write data')

# Create a select.poll() object to listen for incoming standard input data
poll_obj = select.poll()
# Register the standard input sys.stdin with the poll_obj object, specifying select.POLLIN as the event type (listen for input events)
poll_obj.register(sys.stdin, select.POLLIN)

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

# Enter an infinite loop; the select module is used below to perform non-blocking reads and writes
while True:

    # After 10 data reads
    if read_count == 10:
        # Set read_count to 0
        read_count = 0
        # Output the average time taken to send data over the 10 reads
        avg_delta = sum(delta_list) / len(delta_list)
        print("avg time cost : " + str(avg_delta) + " ms\r")

    # Use the poll_obj.poll(1) method to wait for incoming standard input data, with a timeout of 1 ms
    poll_results = poll_obj.poll(1)
    if poll_results:

        # If data has arrived (i.e. poll_results is not empty), read the data from standard input and write it to standard output
        # readline() reads one line of data from standard input (ending with a newline character) and returns a string containing that line
        # The strip() method removes whitespace characters from both ends of the string, including spaces, tabs, newlines, etc.
        # data = sys.stdin.readline().strip()
        # sys.stdin.readline().strip() is a non-blocking read
        # input() is a blocking read and will block program execution
        data = input("please input data : ")

        # Test the time taken to write out the data
        t = time.ticks_us()

        # Write the data to standard output
        # The sys.stdout.write() method can also be used
        # sys.stdout.write("received data : " + data + "\r")
        # sys.stdout.write() writes data directly to the standard output stream without buffering
        # print() first stores the output in a buffer, and only actually outputs it when the buffer is full or a newline character is encountered
        print("received data : " + data + "\r")

        # Calculate the time taken for one read/write
        delta = time.ticks_diff(time.ticks_us(), t)/1000
        # Output the time taken by this read/write
        print("time cost : " + str(delta) + " ms\r")

        # Add the time taken by this read/write to the delta_list list
        delta_list[read_count] = delta
        # Increment the read count by 1
        read_count += 1

    else:
        # If no data has arrived (i.e. poll_results is empty), continue the loop
        continue

Here, we use the select module to monitor standard input; when data arrives, we utilize the print function and input function to complete reading and writing back, meanwhile measure the read-write time consumption and calculate the average value, so as to simulate the data interaction scenario between the USB device and the host.

Burn the code, open the remote terminal, and input data; you can see that the input data is written back to the terminal:

12 USB Universal Serial Bus - Document Tutorial First Draft Copy

3.1 Application Experiment.mp4 22.8 MB

Here, for the convenience of demonstration, we use the blocking input method for reading. In actual data transmission, we expect to read the standard input in a non-blocking manner so as to continuously monitor whether there is data input, and usually the sys.stdin.readline (). strip () method is used for reading. The differences between the two are as follows:

When outputting the received data, we use the familiar print function, but in practical applications, we will adopt the sys.stdout.write () method to ensure real-time performance. The differences between the two are as follows:

References

https://stackoverflow.com/questions/76138267/read-write-data-over-raspberry-pi-pico-usb-cable

https://today.line.me/tw/v2/article/nJXr7M

https://gaoyichao.com/Xiaotu

https://gaoyichao.com/Xiaotu/?book=stm32&title=index

https://toshiba.semicon-storage.com/ap-en/semiconductor/knowledge/e-learning/village/usb-interface-1.html

https://www.circuitbread.com/tutorials/how-usb-works-introduction-part-1

https://en.wikipedia.org/wiki/USB

https://developer.baidu.com/article/details/3197558

https://docs.micropython.org/en/latest/library/machine.USBDevice.html

Version Record

Version Number

Modifier

Time

Content

v1.0.0

Li Zisheng

2025/09/16

Initialize the document, based on MicroPython version V1.23.0.

Only the USB-CDC class has been tested, and the rest have not been tested.

v1.1.0

Li Zisheng

2025/12/15

All the images have been modified completely.