基本函数:
# 串口操作:设置、打开、读取、写入、关闭
com= serial.Serial('com1', 9600, timeout=0.5)
com.open() # 端口:打开
com.isOpen() # 状态:是否已被打开
com.read_all() # 操作:读
com.write(cmd) # 操作:写
com.close() # 端口: 关闭
注意点:写完读取时需要增加延时,当为‘b`’表示没读到。 ?
import binascii
from serial import Serial
if __name__ == "__main__":
com = Serial(port='COM2', baudrate=9600,bytesize=8, parity='N',stopbits=1, #1.实例化串口及各项参数
dsrdtr=False, rtscts=False, xonxoff=False, timeout=2)
if (com.isOpen() == False): #2.查看串口状态 如果串口没打开打开它
com.open()
if (com.isOpen() == True): #3. 如果串口已打开 关了重开
com.close()
com.open()
hexCmd="01 03 06 00 00 10 44 8E"
hexCmd = hexCmd.replace(' ', '') # 去除空格
cmd = binascii.a2b_hex(hexCmd) # 转换为16进制串
write_len = com.write(cmd) #4. Hex发送
print("write:")
print(cmd)
rels = com.read_all() #5.读取
print(rels) #
while True:
rels = com.read_all()
if rels: # 返回不为空 跳出死循环
break
if rels:
print("read:")
print(rels)
?
|