如何通过Raspberry接口进行USB连接

2024-10-17 06:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我试过通过USB线把Arduino连接到raspberry Pi。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 pi2): 注意:自从我尝试了下面显示的许多不同的代码组合后,我已经对不起作用的部分进行了注释

^{pr2}$

Tags: theto代码inechopinserialpi
1条回答
网友
1楼 · 发布于 2024-10-17 06:19:08

首先,你的IF条件看起来不太好。我不明白distance <= minimumRange如何表示路径是清晰的。在

接下来,您正在向串行端口写入一行;该行可以是0\r\n或{}。然后你在读Arduino的一行,返回前面提到的两种可能性中的一种。然后将您读到的行与1进行比较。无论是0\r\n还是{}都不等于1,因此该条件永远不为真也就不足为奇了。您可以通过多种方法解决此问题:

  • Serial.println()更改为Serial.print()
  • arduinoSerialData.readline()更改为arduinoSerialData.readline().rstrip()
  • 将条件更改为if 1 in myData:

另一件要记住的事情是,read()在python3中返回一个bytes对象,而不是python2中的字符串。因此,任何涉及文本的比较都应该确保包含必需的b''信封。比如,如果从读取的数据中去掉CRLF,那么条件应该是if myData == b'1':。在

相关问题 更多 >