阅读串行和用Python响应

时间:2016-10-03 16:25:16

标签: python pyserial

每个人,你好!

我目前正在尝试与我的Arduino(通过Serial连接我的Raspberry Pi)进行通信,并在我的Raspberry Pi上使用我的Python脚本中的信息。

也就是说,我的Python脚本必须等待Arduino在我希望脚本继续之前报告它的数据,但是,我不完全确定如何做到这一点。

这是我到目前为止所得到的:

#!/usr/bin/env python
import time
import serial
import RPi.GPIO as GPIO

ser = serial.Serial('/dev/ttyACM0', 9600)

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(20, GPIO.OUT) #green LED
GPIO.setup(16, GPIO.IN, GPIO.PUD_UP) #green button

GPIO.output(20, True) #green ON

start = time.time()

while True:
        if (GPIO.input(16) == False):
                print "green button pressed"
                time.sleep(0.25)
                start = time.time()
                while (GPIO.input(16) == False):
                        time.sleep(0.01)
                if (GPIO.input(16) == True):
                        print "released!"
                        end = time.time()
                        elapsed = end - start
                        print elapsed
                        if elapsed >= 5:
                                print "longer than 5s"
                        else:
                                print "shorter than 5s"
                                ser.write("0")
                                while True:
                                       print ser.readline().rstrip()
                                       if ser.readline().rstrip() == "a":
                                               print "ready"
                                               continue
                                       if ser.readline().rstrip() == "b":
                                               print "timeout"
                                               break
                                       if ser.readline().rstrip()[0] == "c":
                                               print "validated: " + ser.readline().rstrip()[2]
                                               break

正如你所看到的,我正在向我的Arduino发送数字0,并等待它回复,这意味着它已经准备就绪。之后,当它有数据时,它会发出消息“c”,因此,我需要等待2个不同的单独消息。

我试图通过循环并在我拥有我需要的东西时打破它来做到这一点,但这不起作用。

它目前进入循环,并打印出“a”消息,但不会返回第二条消息。

知道如何正确绑定此循环吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

使用功能

def wait_for(ser,targetChar):
    resp = ""
    while True:
       tmp=ser.read(1)
       resp = resp + tmp
       if not tmp or tmp == targetChar: 
          return resp

first_resp = wait_for(ser,'a')
second_resp = wait_for(ser,'c')
while not second_resp.endswith('c'):
    print "RETRY"
    second_resp = wait_for(ser,'c')

答案 1 :(得分:0)

这对我保持良好的状态非常有效,并且在我得到我想要的东西之前逃脱阻止:

loop = 1
while loop == 1:
      message = ser.readline().rstrip()
if message == "a":
      print "ready"
      continue
if message == "b":
      print "Timeout"
      loop = 0
if message[0] == "c":
      print "Validated: " + message[2]
      loop = 0
if message == "d":
      print "error, try again"
      loop = 0