1、项目研发过程,供产品测试系统使用
2、通讯模块:RS232通讯
3、内容:
3.1、串口连接
3.2、电源模式设置
3.3、通讯命令字拼装和串口写入数据
4、功能实现
4.1、python创建串口
import serial
def CreateSerial(port, baudrate):
"""
创建串口
:param port: type:string 串口号
:param baudrate: type:string 串口波特率
:return: type:boolean 返回串口实例
"""
serialPort = serial.Serial(port, baudrate, timeout=0.05)
serialPort.setRTS(0)
serialPort.parity = serial.PARITY_NONE #无校验
serialPort.bytesize = serial.EIGHTBITS #8个数据位
serialPort.stopbits = serial.STOPBITS_ONE #1个停止位
serialPort.set_buffer_size(10240)
return serialPort
4.2、设置电源模式
import time
def InitSupply(serialPort):
serialPort.write(bytes.fromhex("AA 00 20 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CB")) #设置电源为远程操作模式(20H,值为01)
serialPort.write(bytes.fromhex("AA 00 21 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 CC")) #控制电源输出状态为输出模式(21H,值为01)
serialPort.write(bytes.fromhex("AA 00 22 C3 50 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 DF")) # 电压限制50V,C350
time.sleep(0.3)
4.3、电压命令字的拼接组装
import struct
import re
# 电压串口值转换,Vol为计划输出电压值
def ControlVol(Vol):
commond0 = "AA 00 23 "
commond1 = "00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"
data0 = struct.pack("i", Vol) #struct.pack将Python的Vol电压值根据格式符“i”,转换为字节流(即字节数组)
voltage = [hex(Vol)[2:].rjust(2, '0')+' ' for Vol in data0] #拆解电压值的底字和高字,并转换为十六进制,不足2位补0
command2 = commond0+ voltage[0]+voltage[1]+voltage[2]+voltage[3]+commond1 #前几个字节先拼装一次
command3 = sum([int(i, 16) for i in re.split(' ', command2) if i != '']) #求最后一位校验码
command4 = hex(command3)[3:].rjust(2, '0') #校验码尾数不够补0
command = command2+' '+command4 #所有字节拼装
serialPort.write(bytes.fromhex(command)) #write从串口发送拼装后的数据