我尝试通过USB线将Arduino连接到树莓派。 Arduino板连接到超声波传感器,并根据是否在一定距离内找到障碍物(非常简单的代码)发送0或1的串行消息。问题是这样的:我正在尝试让Raspberry Pi读取Arduino代码并同时播放mp3文件,但由于某些原因似乎不起作用!我不确定问题是否在于编码或者如果Pi可能无法响应从Arduino发送到串行监视器的消息(如果是这样的话会非常难过)。任何帮助将非常感激
这是Arduino代码(我正在使用UNO板):
/*
HC-SR04 Ping distance sensor:
VCC to Arduino
Vin GND to Arduino GND
Echo to Arduino pin 12
Trig to Arduino pin 11 */
#include <NewPing.h> //downloaded from the internet & unzipped in libraries folder in Arduino Directory
#define TRIGGER_PIN 11 // Arduino pin tied to trigger pin on the ultrasonic sensor.
#define ECHO_PIN 12 // Arduino pin tied to echo pin on the ultrasonic sensor.
int maximumRange = 70; // Maximum range needed
int minimumRange = 35; // Minimum range needed
long duration, distance; // Duration used to calculate distance
void setup() {
Serial.begin (9600);
pinMode(TRIGGER_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
}
void loop() {
/* The following trigPin/echoPin cycle is used to determine the distance of the nearest object through reflecting soundwaves off of it */
digitalWrite(TRIGGER_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER_PIN, LOW);
duration = pulseIn(ECHO_PIN, HIGH);
distance = (duration/2) / 29.1; //formula to convert the value measured by the ultrasonic sensor into centimeters
if (distance >= maximumRange || distance <= minimumRange)
{
Serial.println("0"); //means the path is clear
}
else {
Serial.println("1"); //means there is an obstacle in front of the ultrasonic sensor !
}
delay(50); //Delay 50ms before next reading.
}
这是我在Pi中使用的python代码(我有Raspberry Pi 2): 注意:由于我尝试了下面显示的许多不同的代码组合,我已经评论了不起作用的部分
import serial
import RPi.GPIO as GPIO
import sys
import os
from subprocess import Popen
from subprocess import call
import time
import multiprocessing
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
arduinoSerialData = serial.Serial('/dev/ttyACM0', 9600)
while True:
time.sleep(0.01)
if(arduinoSerialData.inWaiting()>0):
myData = arduinoSerialData.readline()
print(myData)
if myData == '1': #THIS IS WHERE THE PROBLEMS START
#os.system('omxplayer sound.mp3') #tried this didn't work
#os.system('python player.py') #which is basically a python program with the previous line in it, also not working!
# I even tried enclosing that part (after if myData == '1') in a while loop and also didn't work !
答案 0 :(得分:0)
首先,您的IF条件看起来不正确。我不知道distance <= minimumRange
如何表明路径是清楚的。
接下来,您正在向串口写入一行;一行可以是0\r\n
或1\r\n
。然后你正在阅读Arduino中的一行,返回上述两种可能性中的一种。然后,您将已阅读的行与1
进行比较。 0\r\n
和1\r\n
都不等于1
,因此条件永远不会出错也就不足为奇了。您可以通过多种方式解决此问题:
Serial.println()
更改为Serial.print()
arduinoSerialData.readline()
更改为arduinoSerialData.readline().rstrip()
if 1 in myData:
要记住的另一件事是,read()
在Python 3中返回一个bytes
对象而不是在Python 2中返回一个字符串。因此,任何涉及文字的比较都应确保包含必需的b''
信封。例如,如果从读取数据中删除CRLF,则您的条件应为if myData == b'1':
。