2017-02-16 96 views
1

我打開4個串口使用這種方法:Pyserial對象進行循環

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' 

但這個工作(少Python化):

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

serListdict不是list並遍歷一個迭代dict的鑰匙。在你的情況下,這些鍵是來自enumerate的整數索引。你可以重複它的值來代替(重命名變量,使其不易混淆)

for ser in serDict.values(): 
    SER_tx_command(ser, set_key, keyList) # send' 

serList詞典的鑰匙使用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' 
+0

這是有道理的 - 將使用它代替。 – user3736436

0
for ser in serList: 

迭代的。在你的情況下,鍵是整數,而不是串行對象。

嘗試:

for ser in serList: 
    SER_tx_command(serList[ser],set_key,keyList) # send' 
+0

這是OP試圖避免的。 – tdelaney

+0

這確實有用,但下面的tdelaney帖子是我可能會用到的。謝謝! – user3736436