003、Python3字符串转成相应的16进制方法(FF---0xFF)
参考资料:https://blog.csdn.net/baidu_37503452/article/details/121506783
data_str = '0102030405060708090a0b0c0d0e0f' data_bin = bytes(bytearray.fromhex(data_str)) print(data_str) print(data_bin)
执行结果如下:
D:\WorkSpace\Code_Space\Arduino_python\day20220328\venv\Scripts\python.exe D:/WorkSpace/Code_Space/Arduino_python/day20220328/demo11.py 0102030405060708090a0b0c0d0e0f b'\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' Process finished with exit code 0
实例代码1:
from time import sleep import serial # 获取充电盒软件版本指令:EF 02 31 22 send_list = [] d1 = 0xef send_list.append(d1) d2 = 0x02 send_list.append(d2) d3 = 0x31 send_list.append(d3) d4 = 0x22 send_list.append(d4) input_s = bytes(send_list) print(input_s) serialPort = "COM28" # 串口 baudRate = 115200 # 波特率 ser = serial.Serial(serialPort, baudRate, timeout=1) print("参数设置:串口=%s ,波特率=%d" % (serialPort, baudRate)) print("====休眠5秒=======") sleep(5) # 发送指令 ser.write(input_s) sleep(1) print("发送指令后的返回结果") num = ser.inWaiting() if num > 0: data = ser.read(num) num = len(data) # hex显示 out_s = '' for i in range(0, len(data)): out_s = out_s + '{:02X}'.format(data[i]) + ' ' print(f"返回结果为:{out_s}。") ser.close() print("end")
实例代码2:
from time import sleep import serial # cmd_str = 'EF023223' # 获取充电盒当前温度 cmd_str = 'EF023122' # 获取充电盒软件版本 # cmd_str = 'EF023021' # 获取充电盒硬件版本 # cmd_str = 'EF02A697' # 获取充电盒PCBA SN号 # cmd_str = 'EF023324' # 获取充电盒固件FW_Checksum # cmd_str = ' EF02B2A3' # 获取充电盒机身镭雕码编号 input_s = bytes(bytearray.fromhex(cmd_str)) print(input_s) serialPort = "COM28" # 串口 baudRate = 115200 # 波特率 ser = serial.Serial(serialPort, baudRate, timeout=1) print("参数设置:串口=%s ,波特率=%d" % (serialPort, baudRate)) print("====休眠5秒=======") sleep(5) # 发送指令 ser.write(input_s) sleep(1) print("发送指令后的返回结果") num = ser.inWaiting() if num > 0: data = ser.read(num) num = len(data) # hex显示 out_s = '' for i in range(0, len(data)): out_s = out_s + '{:02X}'.format(data[i]) + ' ' print(f"返回结果为:{out_s}。") print(type(out_s)) ser.close() print("end")