簡體   English   中英

Python Serial:如何使用 read 或 readline 函數一次讀取 1 個以上的字符

[英]Python Serial: How to use the read or readline function to read more than 1 character at a time

我無法使用我的程序讀取多個字符,我似乎無法弄清楚我的程序出了什么問題。

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)
count=1

while True:
    for line in ser.read():

        print(str(count) + str(': ') + chr(line) )
        count = count+1

ser.close()

這是我得到的結果

connected to: COM5
1: 1
2: 2
3: 4
4: 3
5: 1

其實我期待這個

connected to: COM5
1:12431
2:12431

像上面提到的那樣可以同時讀取多個字符而不是一個一個。

我看到了幾個問題。

第一的:

ser.read() 一次只返回 1 個字節。

如果您指定一個計數

ser.read(5)

它將讀取 5 個字節(如果在 5 個字節到達之前發生超時,則更少。)

如果您知道您的輸入總是以 EOL 字符正確終止,更好的方法是使用

ser.readline()

這將繼續讀取字符,直到收到 EOL。

第二:

即使您讓 ser.read() 或 ser.readline() 返回多個字節,由於您正在迭代返回值,您仍將一次處理一個字節。

擺脫

for line in ser.read():

然后說:

line = ser.readline()

串行一次發送 8 位數據,轉換為 1 個字節,1 個字節表示 1 個字符。

您需要實現自己的方法,該方法可以將字符讀入緩沖區,直到到達某個哨兵為止。 約定是發送一條消息,如12431\\n指示一行。

因此,您需要做的是實現一個緩沖區,該緩沖區將存儲 X 個字符,一旦到達該\\n ,就在該行上執行您的操作並繼續將下一行讀入緩沖區。

請注意,您必須處理緩沖區溢出的情況,即當接收到的線路比您的緩沖區長時等...

編輯

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

我用這個小方法用 Python 讀取 Arduino 串口監視器

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

我從我的 arduino uno 收到了一些日期(0-1023 數字)。 使用來自 1337holiday、jwygralak67 的代碼和其他來源的一些提示:

import serial
import time

ser = serial.Serial(
    port='COM4',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
seq = []
count = 1

while True:
    for c in ser.read():
        seq.append(chr(c)) #convert from ANSII
        joined_seq = ''.join(str(v) for v in seq) #Make a string from array

        if chr(c) == '\n':
            print("Line " + str(count) + ': ' + joined_seq)
            seq = []
            count += 1
            break


ser.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM