Python'ser.write'在Windows上永久暂停程序,可能有错误吗?

2024-04-27 21:58:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用python代码与arduino通信,串行传输大量字节。下面的代码是我的主要函数,它一直工作到第一个或第二个'ser.wrte'函数之后。令人困惑的是,该程序在mac上正常工作,没有错误,但在任何运行windows的笔记本电脑上都存在上述问题(版本7和版本10已经过测试,但没有成功)是否有任何基于代码的原因,或者是由于与windows相关的串行端口问题

#Communicates to arduino via serial port
def pump():
print('****************')
if len(seq) == 0:
    print("EmptySeqError: please store patterns in the sequence before sending it!")
    return
#######################
port = "COM17"
macport = "/dev/cu.usbmodem1411"
baudrate = 9600
####################### 
try:
    ser = serial.Serial(port, baudrate, timeout=0.1) #, write_timeout=0.1)
except serial.SerialException:
    print('SerialException: cannot create serial object')
    return
else:
    if ser.isOpen():
        print('serial port {} is opened successfully!'.format(ser.name))
for json in seq:
    MSB = int(json['Hex Code MSB'], 16)
    LSB = int(json['Hex Code LSB'], 16)
    V = int(json['Voltage'], 16) #For voltage transmission
    Vlsb = V & 0xff              #Voltage LSB
    Vmsb = (V>>8) & 0xff         #Voltage MSB
    print(V, 'in hex =', hex(V))
    print(Vlsb, 'in hex =', hex(Vlsb))
    print(Vmsb, 'in hex =', hex(Vmsb))
    #X = int(json['Xhigh'], 16)
    #Y = int(json['Ybase'], 16)
    #Z = int(json['Zsec'], 16)
    HD = int(json['High Delay'], 16)
    LD = int(json['Low Delay'], 16)
    print("**************")
    print("(MSB/LSB) number of bytes written: ", ser.write(bytes([MSB, LSB])))
    print("(Voltage) number of bytes written: ", ser.write(bytes([Vmsb,Vlsb])))
    print("(HD/LD) number of bytes written: ", ser.write(bytes([HD, LD])))
print("serial is closing...")
sys.stdout.flush()
ser.close()
#End of sending

Tags: injsonbytesportserialserwriteint