Micropython-based on Micro-USB port to achieve serial communication with UART upper and lower computers

In fact, the USB port of Micropython is essentially a UART, that is, UART0, which is not on the board, so here we only need to use a built-in pyb class pyb.USB_VCP to control the VCP through functions and communicate with the PC.

pyb.USB_VCP

For a long time, when using the USB serial port, you can directly use the print function to realize the data sending function of the single-chip microcomputer in the USB serial port, but it cannot realize the data receiving function sent by the host computer, so the data reading can be achieved well with VCP And send function.

ALL 端

When using pyb.USB_VCPit, you only need to declare it first, and then it will basically use the same method as the UART API.

import pyb
# 声明类
usb_vcp = pyb.USB_VCP()
# 检查是否连接
print(usb_vcp.isconnected())

while True:
    # 每秒发送一次,测试上位机是否能收到
    b = ("b"+"\n").encode("utf-8")
    usb_vcp.send(b)
    pyb.delay(1)

Host computer code

The upper computer can directly test whether it can receive the code put on by the lower computer.

import serial

if __name__ == '__main__':
    ser = serial.Serial('COM1', 9600)
    while 1:
        a = "a".encode("utf-8")
        ser.write(a)
        b = ser.readline()#read a string from port
        b = b.decode("utf-8")
        print(b)

Test reception: completely ok!
Insert picture description here

However, there is a disadvantage that it may conflict with the serial port during debugging. If the product development is about the same, you can directly use the USB as the serial port, which is very easy to use.

Reference article:

Guess you like

Origin blog.csdn.net/qq_45779334/article/details/114590459