用UART应用实例说明MicroPython-ESP32串口通信方式

UART构造器

不同于其他MicroPython开发板,ESP32可以自定义管脚作为UART, 不过ESP32自身只有两个UART资源。

导入UART 模块

from machine import UART

UART对象的构造器函数:

UART(id, baudrate, bits, parity, rx, tx, stop, timeout)
id : 串口编号

ESP32的UART资源只有两个, id有效取值范围为1,2

bandrate: 波特率(时钟频率)

常用波特率为: ○ 9600 (默认) ○ 115200 信息接受双方的波特率必须一致,否则会乱码。

bits:单个字节的位数(比特数)

○ 8 (默认) ○ 7 ○ 9

parity: 校验方式

○ None 不进行校验(默认) ○ 0 偶校验 ○ 1 奇校验

rx:接收口的GPIO编号

在ESP32上面很多个管脚都可以自定义为UART管脚有效GPIO编号如下:

0,2,4,5,9,10, 12-19, 21-23,25, 26, 34-36, 39
tx:发送口的GPIO编号

有效GPIO管脚编号同rx

stop: 停止位个数

○ 1 (默认) ○ 2

timerout: 超时时间

取值范围: 0 < timeout ≤ 2147483647

from machine import UART
uart = UART(2, baudrate=115200, rx=13,tx=12,timeout=10)
uart.read(10)        # read 10 characters, returns a bytes object
                    # 读入10个字符, 返回一个比特对象
uart.read()            # read all available characters
                    # 读取所有的有效字符
uart.readline()        # read a line
                    # 读入一行
uart.readinto(buf)  # read and store into the given buffer
                    # 读入并且保存在缓存中
uart.write(abc)    # write the 3 characters
                    # 向串口写入3个字符abc
uart.readchar()     # read 1 character and returns it as an integer
                    # 读入一个字符
uart.writechar(42)  # write 1 character
                    # 写入ASCALL码为42的字符
uart.writechar(ord(*)) # 等同于uart.writechar(42)

#检测串口是否有数据
uart.any()          # returns the number of characters waiting

ESP32串口自发自收实验 接线 将开发板的 13号引脚与12号引脚用杜邦线相连接

ESP32串口通信-字符串数据自发实验

接线 将开发板的 13号引脚与12号引脚用杜邦线相连接。


from machine import UART,Pin
import utime

# 初始化一个UART对象
uart = UART(2, baudrate=115200, rx=13,tx=12,timeout=10)

count = 1

while True:
    print(

===============CNT {}===============.format(count))

    # 发送一条消息
    print(Send: {}.format(hello {}
.format(count)))
    print(Send Byte :) # 发送字节数
    uart.write(hello {}
.format(count))
    # 等待1s钟
    utime.sleep_ms(1000)

    if uart.any():
        # 如果有数据 读入一行数据返回数据为字节类型
        # 例如  bhello 1

        bin_data = uart.readline()
        # 将手到的信息打印在终端
        print(Echo Byte: {}.format(bin_data))

        # 将字节数据转换为字符串 字节默认为UTF-8编码
        print(Echo String: {}.format(bin_data.decode()))
    # 计数器+1
    count += 1
    print(---------------------------------------)

输出

===============CNT 1===============
Send: hello 1

Send Byte :
8
Echo Byte: bhello 1

Echo String: hello 1

---------------------------------------


===============CNT 2===============
Send: hello 2

Send Byte :
8
Echo Byte: bhello 2

Echo String: hello 2

---------------------------------------


===============CNT 3===============
Send: hello 3

Send Byte :
8
Echo Byte: bhello 3

Echo String: hello 3

---------------------------------------
经验分享 程序员 微信小程序 职场和发展