Python Serial:如何使用 read 或 readline 函数一次读取 1 个以上的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16077912/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:43:47  来源:igfitidea点击:

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

pythonserial-portreadlinepyserial

提问by user2294001

I'm having trouble to read more than one character using my program, I can't seem to figure out what went wrong with my program.

我无法使用我的程序读取多个字符,我似乎无法弄清楚我的程序出了什么问题。

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()

here are the results I get

这是我得到的结果

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

actually I was expecting this

其实我期待这个

connected to: COM5
1:12431
2:12431

something like the above mentioned which is able read multiple characters at the same time not one by one.

像上面提到的那样可以同时读取多个字符而不是一个一个。

回答by 1337holiday

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

串行一次发送 8 位数据,转换为 1 个字节,1 个字节表示 1 个字符。

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\nindicating one line.

您需要实现自己的方法,该方法可以将字符读入缓冲区,直到到达某个哨兵为止。约定是发送一条消息,例如12431\n指示一行。

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

因此,您需要做的是实现一个缓冲区,该缓冲区将存储 X 个字符,一旦达到该值\n,就在该行上执行操作并继续将下一行读入缓冲区。

Noteyou will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

请注意,您必须处理缓冲区溢出的情况,即当接收到的线路比您的缓冲区长时等...

EDIT

编辑

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()

回答by jwygralak67

I see a couple of issues.

我看到了几个问题。

First:

第一的:

ser.read() is only going to return 1 byte at a time.

ser.read() 一次只返回 1 个字节。

If you specify a count

如果您指定一个计数

ser.read(5)

it will read 5 bytes (less if timeout occurrs before 5 bytes arrive.)

它将读取 5 个字节(如果在 5 个字节到达之前发生超时,则更少。)

If you know that your input is always properly terminated with EOL characters, better way is to use

如果您知道您的输入总是以 EOL 字符正确终止,更好的方法是使用

ser.readline()

That will continue to read characters until an EOL is received.

这将继续读取字符,直到收到 EOL。

Second:

第二:

Even if you get ser.read() or ser.readline() to return multiple bytes, since you are iterating over the return value, you will still be handling it one byte at a time.

即使您让 ser.read() 或 ser.readline() 返回多个字节,由于您正在迭代返回值,您仍将一次处理一个字节。

Get rid of the

摆脱

for line in ser.read():

and just say:

然后说:

line = ser.readline()

回答by Desprit

I was reciving some date from my arduino uno (0-1023 numbers). Using code from 1337holiday, jwygralak67 and some tips from other sources:

我从我的 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()

回答by Thushara Madushan

I use this small method to read Arduino serial monitor with Python

我用这个小方法用 Python 读取 Arduino 串口监视器

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