昨天在做串口通信時候發現,串口參數(timeout=1 || timeout=0.01)對通信的讀數據竟然影響很大,代碼如下:
self.ser = serial.Serial(port=serialName, timeout=0.01, baudrate=115200, parity=serial.PARITY_ODD)
- timeout = 1:串口讀取數據特別慢
- timeout = 0.01:串口讀取數據正常
嚇得我趕緊查看下官方文檔:
- timeout = None: wait forever / until requested number of bytes are received
- timeout = 0: non-blocking mode, return immediately in any case, returning zero or more, up to the requested number of bytes
- timeout = x: set timeout to x seconds (float allowed) returns immediately when the requested number of bytes are available, otherwise wait until the timeout expires and return all bytes that were received until then.
顯然,我個人用的就是第三種賦值方法,這個解釋就是:在設定的timeout時間范圍內,如果讀取的字節數據是有效的(就是非空)那就直接返回,否則一直會等到這個設定的timeout時間並返回這段時間所讀的全部字節數據。
分析下代碼:
#read data
def ReadData(self,timeDelay): bReadData = False for i in range(0, 5, 1): time.sleep(timeDelay) readString = self.ser.readline() if(len(readString) > 1): return readString else: continue
if(bReadData == False): return "fail"
發現讀取數據用的是readline()這個函數,那具體實現機制會是怎樣呢,個人理解如下:
1、Python2的內置編碼是ASCII碼
2、官方文檔給出的解釋是針對一串字符串而言,但readline()函數的操作對象肯定是單字節
3、單字節在讀取的時候是有一定的時間間隔的,即讀完一個字節隔段時間再讀一個字節
4、這個時間間隔很有可能和timeout值成正比