我用这种方法打开4个串口:
ComPorts = ['com11','com13','com7','com19']
stimeout = 0.000120 ## 120 us character timeout
baud = 115200
serList = {}
set_key = 0x0E
keyList = [0,0,0,0,0,0,0,0,0]
for idx,com in enumerate(ComPorts): ## open up the COM ports
serList[idx] = serial.Serial(com,baud,timeout=stimeout)
我想向所有端口写一条公共消息 - 这失败了:
for ser in serList:
SER_tx_command(ser,set_key,keyList) # send'
但这有效(不那么pythonic):
for idx in range(len(ComPorts)):
SER_tx_command(serList[idx],set_key,keyList) # send
这个常见功能给出错误:
def SER_tx_command(ser,cmd,payload):
length = len(payload)+4;
cksum = (0x01 + length + cmd)&0x00FF
msg = [0x01,length,cmd]
if (length > 4):
for val in payload:
cksum = (cksum+val)&0x00FF
msg.extend([val])
msg.extend([cksum])
for val in msg:
ser.write(chr(val)) ### ERROR HERE ###
错误讯息:
Traceback (most recent call last):
File "packet_test02.py", line 468, in <module>
update_key(key_jump)
File "packet_test02.py", line 149, in update_key
SER_tx_command(ser,set_key,keyList) # send the packet msg
File "packet_test02.py", line 28, in SER_tx_command
ser.write(chr(val))
AttributeError: 'int' object has no attribute 'write'
如何让循环迭代串口对象?
或者使用python是不可能的,我必须使用索引迭代器方法吗?
答案 0 :(得分:0)
serList
是dict
而不是list
并且迭代dict
会迭代其键。在您的情况下,键是来自enumerate
的整数索引。您可以改为迭代其值(并重命名该变量以减少其混淆)
for ser in serDict.values():
SER_tx_command(ser, set_key, keyList) # send'
或使用list
代替dict
ComPorts = ['com11','com13','com7','com19']
stimeout = 0.000120 ## 120 us character timeout
baud = 115200
set_key = 0x0E
keyList = [0,0,0,0,0,0,0,0,0]
serList = [serial.Serial(com,baud,timeout=stimeout) for com in ComPorts] ##
for ser in serList:
SER_tx_command(ser, set_key, keyList) # send'
答案 1 :(得分:0)
for ser in serList:
遍历serList
字典中的键。在您的情况下,键是整数,而不是串行对象。
尝试:
for ser in serList:
SER_tx_command(serList[ser],set_key,keyList) # send'