Python串口测试:bytes数据

在执行串口测试任务时,PC端向下位机发送串口指令有两种常用的格式:

  • ASCII字符串,比如:AT+CFUN=1
  • 整数数组,比如:[0x59, 0x03, 0x01, 0x02, 0x03]

在Python程序中,PySerial库的数据收发API的参数都是bytes类型。

Python的bytes类型是一个只读的字节列表,单个字节就相当于C语言的uint8类型。bytes的常见写法为:b'\x01\x02'b'hello'

所以在实际程序中需要将字符串或整数类型与bytes进行互转,本文总结一些常用的转换技巧。

1. 字符串转换成bytes类型

cmd_str = 'AT+CFUN=1'
cmd_bytes = cmd_str.encode() 
# cmd_bytes = b'AT=CFUN=1'

2. 十六进制数组转换成bytes类型

cmd_hex = [0x01, 0x02, 0x03, 0x04]
cmd_bytes = bytes(cmd_hex) 
# cmd_bytes = b'\x01\x02\x03\x04'

cmd_byte = 0x05
cmd_bytes = bytes([cmd_byte]) 
# cmd_bytes = b'\x05'

3. 多字节整数转换成bytes类型

cmd_number = 0x010203
cmd_bytes = cmd_number.to_bytes(3, 'big') 
# cmd_bytes = b'\x01\x02\x03'

4. bytes类型转换成整数数组

cmd_bytes = b'\x01\x02\x03\x04'
cmd_hex_list = list(cmd_bytes) 
# cmd_hex_list = [0x01, 0x02, 0x03, 0x04]

cmd_bytes = b'\x05'
cmd_byte = cmd_bytes[0] 
# cmd_byte = 0x05

5. bytes类型转换成字符串数组(十六进制形式)

cmd_bytes = b'\xf1\xf2\xf3\xf4'
cmd_str = ['0x{:02X}'.format(x) for x in list(cmd_bytes)] 
# cmd_str = ['0xF1', '0xF2', '0xF3', '0xF4']

6. bytes类型转换成ASCII字符串

cmd_bytes = b'hello'
cmd_str = cmd_bytes.decode()
# cmd_str = 'hello'

7. bytes类型转换成多字节整数

cmd_bytes = b'\x00\x01'
cmd_hex = int.from_bytes(cmd_bytes, 'big')
# cmd_hex = 0x0001

示例

准备一个PCA10040,下载<sdk 16.0>\examples\peripheral\cli,用串口终端连接测试,输入python命令,将返回Nice joke ;),实际效果如下:

下面脚本可以自动通常串口发送python命令,然后打印出设备返回的消息Nice Joke ;)

import serial

CMD_COLORS_OFF = 'cli colors off'
CMD_PYTHON = 'python'
CLI_PREFIX = 'uart_cli:~$ '

def serial_command(cmd):
    serial_cmd = cmd + '\r'
    return bytes(serial_cmd.encode())

if __name__ == '__main__':
    serial_port = serial.Serial(port='COM34', baudrate=115200, timeout=0.1)
    # disable color
    serial_port.write(serial_command(CMD_COLORS_OFF))
    # send python command
    serial_port.write(serial_command(CMD_PYTHON))
    
    recv_msg = ''
    while True:
        read_line = serial_port.readline()
        if read_line == CLI_PREFIX.encode():
            print('Command finished')
            break
        if read_line != b'':
            recv_msg += read_line.decode()
    print('Message: {}'.format(recv_msg))

(完)

留下评论

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据