Raspberry pi和Arduino之间的串行通信失败

时间:2017-10-18 10:48:36

标签: arduino raspberry-pi raspberry-pi3 pyserial

我正在制作一个项目,其中我将Arduino Uno和Rasberry pi连接到用于连接Arduino和PC的简单usb。我正在尝试仅在我需要使用此代码时才读取传感器: -

pi@raspberrypi:~/project $ python3
Python 3.5.3 (default, Jan 19 2017, 14:11:04)
[GCC 6.3.0 20170124] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import serial
>>> ser = serial.Serial('/dev/ttyACM0', 9600)
>>> ser.write(b'sensors')
7
>>> input = ser.readline()
>>> print(input)
b'37.20 32.50 0 995\r\n'
>>>

但是当我在python文件中放入相同的代码并尝试运行它时,它只会卡在ser.readline()上。在添加超时时,它只返回一个空字符串。 python文件代码是: -

import serial

ser = serial.Serial("/dev/ttyACM0", 9600)

ser.write(b'sensors')
input = ser.readline()
print(input)

任何人都可以帮助我吗? 我知道写消息正在到达Arduino,因为我能够轻松地启动led和其他组件。 Raspberry pi只是没有阅读Arduino的消息。

我的Arduino代码是: -

#include <DHT.h>;
#define DHTPIN 2     // what pin we're connected to
#define DHTTYPE DHT22 
DHT dht(DHTPIN, DHTTYPE);

int rain_sensor_pin = 4;
int led_pin = 13;
int ldr_pin = A0;
float hum, temp;
int rain, ldr;
String message;

void setup() {
  Serial.begin(9600);
  pinMode(rain_sensor_pin, INPUT);
  pinMode(led_pin, OUTPUT);
  digitalWrite(led_pin, LOW);
  dht.begin(); 
}

void loop() {
  if(Serial.available()){
    message = Serial.readString();
    message_action();
  }
}

void message_action(){
  if(message == "sensors"){
    sensors();
  }else {
    action();
  }
}

void sensors(){
  hum = dht.readHumidity();
  temp= dht.readTemperature();
  rain = digitalRead(rain_sensor_pin);
  ldr = analogRead(ldr_pin);
  Serial.println(String(hum) + " " + String(temp) + " " + String(rain) + " " + String(ldr));
}

void action(){
  if (message == "light_on"){
    digitalWrite(led_pin, HIGH);
  }else if (message == "light_off"){
    digitalWrite(led_pin, LOW);
  }
}

0 个答案:

没有答案