Python pyserial 中 Serial.available() 的等价物是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38645060/
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
What is the equivalent of Serial.available() in pyserial?
提问by Michael Molter
When I am trying to read multiple lines of serial data on an Arduino, I use the following idiom:
当我尝试在 Arduino 上读取多行串行数据时,我使用以下习语:
String message = "";
while (Serial.available()){
message = message + serial.read()
}
In Arduino C, Serial.available()
returns the number of bytes available to be read from the serial buffer (See Docs). What is the equivalent of Serial.available()
in python?
在 Arduino C 中,Serial.available()
返回可从串行缓冲区读取的可用字节数(请参阅文档)。python中的等价物是Serial.available()
什么?
For example, if I need to read multiple lines of serial data I would expect to ues the following code:
例如,如果我需要读取多行串行数据,我希望使用以下代码:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050)
...
while ser.available():
print ser.readline()
回答by Rob?
The property Serial.in_waiting
returns the "the number of bytes in the receive buffer".
该属性Serial.in_waiting
返回“接收缓冲区中的字节数”。
This seems to be the equivalent of Serial.available()
's description: "the number of bytes ... that's already arrived and stored in the serial receive buffer."
这似乎相当于Serial.available()
的描述:“字节数......已经到达并存储在串行接收缓冲区中。”
Try:
尝试:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout=0.050)
...
while ser.in_waiting: # Or: while ser.inWaiting():
print ser.readline()
For versions prior to pyserial 3.0, use .inWaiting()
. To determine your pyserial version, do this:
对于 pyserial 3.0 之前的版本,请使用.inWaiting()
. 要确定您的 pyserial 版本,请执行以下操作:
import serial
print(serial.__version__)
回答by Ajit Nayak
I have written my code as below. Hope you can use it modify your code
我写了我的代码如下。希望你可以使用它修改你的代码
import serial
import csv
import os
import time
import sys
import string
from threading import Timer
def main():
pass
if __name__ == '__main__':
main()
COUNT=0
f=open("test.csv","w+");
result = csv.writer(f,delimiter=',')
result_statement=("Dir","ACTUATOR_ON_OFF","MODE","DATE","TIME"," TRACKER DESIRED ANGLE"," TRACKER ACTUAL ANGLE")
result.writerow(result_statement)
f.close()
while COUNT<=100:
#while():
time.sleep(60)
ser=serial.Serial()
ser.port=12
ser.baudrate=9600
ser.open()
str=ser.read(150)
# print "string are:\n",str
print type(str)
val=str.split(":")
# print "value is:\n",val
lines=str.split("\r\n")
# print "line statement are :\n",lines
COUNT=COUNT+1
print COUNT
f=open("test.csv","a+");
result = csv.writer(f,delimiter=',')
wst=[]
for line in lines[:-1]:
parts=line.split(":")
for p in parts[1:]:
wst.append(p)
#result = csv.writer(f,delimiter=',')
#wst.append(parts[1:])
print "wst:\n",wst
result.writerow(wst)
f.close()
f.close()
ser.close()
回答by Evaldas22
I solved the same problem like so. The only drawback of this code is that when the first time I'm sending letter 'a', ser.inWaiting() will return 0. To remove this effect I added delay of 1 second before it. That seems to solve the problem.
我像这样解决了同样的问题。这段代码的唯一缺点是,当我第一次发送字母 'a' 时,ser.inWaiting() 将返回 0。为了消除这种影响,我在它之前添加了 1 秒的延迟。这似乎解决了问题。
In my case, ATmega16 sends back a string either 8 or 12bits. So, I will get the number of bits arriving to RPi with ser.inWaiting() and then I'll read that much data with ser.read(), combining them into ser.read(ser.inWaiting())
就我而言,ATmega16 发回一个 8 位或 12 位的字符串。因此,我将使用 ser.inWaiting() 获得到达 RPi 的位数,然后我将使用 ser.read() 读取那么多数据,将它们组合成 ser.read(ser.inWaiting())
import RPi.GPIO as GPIO
from time import sleep
import serial # version is 3.2.1
ser = serial.Serial('/dev/rfcomm0', 9600)
ser.parity = serial.PARITY_ODD
ser.parity = serial.PARITY_NONE
GPIO.setmode(GPIO.BOARD)
led1 = 16
led2 = 18
button = 7
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)
GPIO.setup(button, GPIO.IN, pull_up_down = GPIO.PUD_UP)
try:
while True:
choice = raw_input("Enter 'a' if you want to turn LED ON or 'b' "
+ "to turn the LED OFF: ")
if (choice == "a"):
print "Sending command to turn LED ON"
GPIO.output(led1, GPIO.HIGH)
sleep(1)
GPIO.output(led1, GPIO.LOW)
#Send the actual data
ser.write('a');
#Receive what ATmega it send back
sleep(1)
received_data = ser.read(ser.inWaiting())
print "Received data: " + received_data
elif (choice == "b"):
print "Sending command to turn LED OFF"
GPIO.output(led2, GPIO.HIGH)
sleep(1)
GPIO.output(led2, GPIO.LOW)
#Send the actual data
ser.write('b');
#Receive what ATmega it sends back
sleep(1)
received_data = ser.read(ser.inWaiting())
print "Received data: " + received_data
else:
print "Invalid command"
GPIO.output(led1, GPIO.HIGH)
GPIO.output(led2, GPIO.HIGH)
sleep(.3)
GPIO.output(led1, GPIO.LOW)
GPIO.output(led2, GPIO.LOW)
sleep(.3)
GPIO.output(led1, GPIO.HIGH)
GPIO.output(led2, GPIO.HIGH)
sleep(.3)
GPIO.output(led1, GPIO.LOW)
GPIO.output(led2, GPIO.LOW)
#send invalid command
ser.write(choice);
#receive what ATmega sends back
sleep(1)
received_data = ser.read(ser.inWaiting())
print "Received data: " + received_data
finally:
GPIO.cleanup()
回答by jaydublu2002
A correct answer will depend on the version of Python - this has tripped me up for some time today. I suspect some of the comments were running on Raspberry Pi which is currently at Python 2.7.9 and similarly less-than-current pySerial.
正确的答案将取决于 Python 的版本 - 今天这让我感到困惑有一段时间了。我怀疑一些评论是在 Raspberry Pi 上运行的,它目前在 Python 2.7.9 和类似的低于当前的 pySerial。
So on a Pi you might use ser.inWaiting()
which is similar to Serial.available()
in Arduino C - both return the number of bytes in the receive buffer; for pySerial >= 3.0 you use ser.in_waiting
(note this is an attribute not a function - http://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.in_waiting)
因此,在 Pi 上,您可能会使用ser.inWaiting()
类似于Serial.available()
Arduino C的 Pi - 两者都返回接收缓冲区中的字节数;对于 pySerial >= 3.0 您使用ser.in_waiting
(请注意,这是一个属性而不是函数 - http://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.in_waiting)
Incidentally, on a Pi (and presumably older Pythons/pySerials) import serial ; print (serial.__version__)
results in an attribute error but works on newer versions.
顺便说一句,在 Pi(可能是较旧的 Pythons/pySerials)上会import serial ; print (serial.__version__)
导致属性错误,但适用于较新的版本。