我尝试通过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 !
1 回答
首先,您的IF条件不会显示
distance <= minimumRange
表示路径是否清晰 .接下来,您正在向串口写入一行;一行可以是
0\r\n
或1\r\n
. 然后你're reading a line from the Arduino, returning one of the two aforementioned possibilities. You'然后比较你读过的行到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':
.