【发布时间】:2016-10-22 08:47:16
【问题描述】:
我尝试通过 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 !
【问题讨论】:
-
缩进是Python中的代码;它的缺乏使您的代码不仅难以理解,而且容易被误解。编辑您的问题。
标签: python linux arduino raspberry-pi