读取序列并用 Python 响应

Reading serial and responding with Python

大家好!

我目前正在尝试与我的 Arduino(它通过串行连接到我的 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

如您所见,我将数字 0 发送到我的 Arduino,并等待它以 a 响应,这意味着它已准备就绪。之后,当它有数据时,它会发出消息 "c",结果,我需要等待 2 条不同的消息。

我试过通过创建一个循环并在我有需要的时候打破它来做到这一点,但这不起作用。

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

知道如何正确连接这个循环吗?

谢谢!

使用函数

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

这对我来说很有效,可以让我保持一段时间,并逃离封锁,直到我得到我想要的东西:

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