下面是用Python写的测试代码
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
单元测试:Python串口发送中文,SSCOM串口助手接收,看在UTF-8、GB2312、GBK三种编码下SSCOM助手对于中文的支持程度。
"""
import serial
if __name__ == "__main__":
try:
port = "COM15" # Win Os use COM?; Linux OS use /dev/tty???
bps = 115200
wait_time = 5
serial_0 = serial.Serial(port, bps, timeout=wait_time)
print("打开的串口参数:", serial_0)
print(serial_0.port)
print(serial_0.baudrate)
result = serial_0.write("\n".encode("ASCII"))
print("写字节数:",result)
serial_0_send_bytes_count = result
if True:
result = serial_0.write("全志民\n".encode("UTF-8"))
print("写字节数:", result)
serial_0_send_bytes_count += result
if True:
result = serial_0.write("全志民\n".encode("GB2312"))
print("写字节数:", result)
serial_0_send_bytes_count += result
if True:
result = serial_0.write("全志民\n".encode("GBK"))
print("写字节数:", result)
serial_0_send_bytes_count += result
print("serial_0_send_bytes_count = ",serial_0_send_bytes_count)
except Exception as e:
print("异常:", e)
测试结果如下图所示(Win10)
测试结果如下图所示(树莓派4)
注意串行端口号的写法(在WIN和LINUX下是不同的)
结果分析
1)Python脚本文本文件的字符编码用的是UTF-8(没有BOM),在用串口发送时通过encode()函数把UTF-8编码转换为指定编码,再发送出去。
2)SSCOM串口助手能正确解释GBK和GB2312,但是不能解释出UTF-8。
3)很多的串口助手都不能很好地显示UTF-8编码,这是在用串口调试时需要注意的。