我建議創建一個新的對象串行一次,讀多次,根據需要:
import serial, time
try:
station1 = serial.Serial('/dev/ttyUSB0', 9600)
print 'station one Is Ready!! Please Show your Card'
except serial.SerialException:
print 'Station 1 is Down'
while True:
card_dataa = station1.read(12)
print card_dataa
您也可以選擇設置爲0超時:
import serial, time
try:
station1 = serial.Serial('/dev/ttyUSB0', 9600,timeout=0)
print 'station one Is Ready!! Please Show your Card'
except serial.SerialException:
print 'Station 1 is Down'
while True:
card_dataa = station1.read(12)
if len(card_dataa) > 0: print card_dataa
你也應該能夠輕鬆地在同一程序打開2個串行連接:
import serial, time
station1 = None
station2 = None
try:
station1 = serial.Serial('/dev/ttyUSB0', 9600,timeout=0)
print 'station 1 Is Ready!! Please Show your Card'
except Exception,e:
print 'Station 1 is Down',e
try:
station2 = serial.Serial('/dev/ttyUSB1', 9600,timeout=0)
print 'station 2 Is Ready!! Please Show your Card'
except Exception,e:
print 'Station 2 is Down',e
while True:
if station1 != None:
card_dataa1 = station1.read(12)
if len(card_dataa1) > 0: print card_dataa1
if station2 != None:
card_dataa2 = station2.read(12)
if len(card_dataa2) > 0: print card_dataa2
這意味着第二個閱讀器會在打印之前等待第一個閱讀器完成,這就是fingaz推薦的穿線方式。
這裏是概念的基本評價證明了穿線:
import threading,time,serial
#subclass threading.Thread
class RFIDSerialThread(threading.Thread):
SLEEP_TIME = 0.001 #setup sleep time (update speed)
#constructor with 3 parameters: serial port, baud and a label for this reader so it's easy to spot
def __init__(self,port,baud,name):
threading.Thread.__init__(self) #initialize this instance as a thread
self.isAlive = False #keep track if the thread needs to run(is setup and able to go) or not
self.name = name #potentially handy for debugging
self.data = "" #a placeholder for the data read via serial
self.station = None #the serial object property/variable
try:
self.station = serial.Serial(port,baud,timeout=0) #attempt to initialize serial
self.isAlive = True #and flag the thread as running
except Exception,e:
print name + " is Down",e #in case of errors print the message, including the station/serial port
def run(self): #this gets executed when the thread is started
while self.isAlive:
if self.station != None: self.data = self.station.read(12) #read serial data
time.sleep(RFIDSerialThread.SLEEP_TIME)
if __name__ == '__main__':
#initialize the two readers
station1 = RFIDSerialThread('/dev/ttyUSB0',9600,"station #1")
station2 = RFIDSerialThread('/dev/ttyUSB1',9600,"station #2")
#start the threads
station1.start()
station2.start()
while True:#continously print the data (if any)
if len(station1.data) > 0: print station1.name,station1.data
if len(station2.data) > 0: print station2.name,station2.data
請注意,我沒有附加實際的硬件進行測試,所以這可能不是作爲是工作,但應該提供足夠的信息來進行。
我也建議嘗試物理距離的讀者。根據讀者和他們的能力,他們可能會互相干擾,這可能會導致錯誤的數據。如果您仍然遇到混亂的數據問題,我會嘗試通過一些假設來找出問題所在(例如問題是硬件(讀卡器干擾,讀卡器損壞,USB連接器鬆動等)還是軟件問題(串口未正確初始化/刷新/等),一次取出一件東西)
非常感謝您先生!答案非常具有說服力。現在它不給我任何混亂的輸出。 –
主席先生,當閱讀完成後,我想向站發送一些字符。你能幫我嗎 –
我建議你發佈一個單獨的問題,解釋你想要達到什麼,你如何嘗試,以及什麼問題/你在這樣做遇到的錯誤。 –