【问题标题】:Communication between Arduino and Raspberry Pi over USBArduino 和 Raspberry Pi 通过 USB 进行通信
【发布时间】:2014-02-21 19:35:05
【问题描述】:

我有一个通过 USB 与 Raspberry Pi 连接的 Arduino。 Python 程序通过 USB 发送一个值,然后 arduino 接收它并打开 LED。 Arduino 正在将模拟值从 A0 发送到 Raspberry 上的 Python 程序。但是 Python 有时会收到 024244 而不是 1024。我怎样才能解决这个问题?这是我的代码: http://www.bitsharr.com/Hsoxw7nG

Arduino 代码:

int led = 13;
char  charIn;

int sensorPin = A0;    // select the input pin for the potentiometer
int sensorValue = 0;  // variable to store the value coming from the sensor
long previousMillis = 0; 
long interval = 1000;  
// the setup routine runs once when you press reset:

void setup() {           
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);  
  Serial.begin(9600); //This initializes the USB as a serial port
}

void loop() {
  if (Serial.available()) {
    delay(5); // warten bis alle Daten da sind
    while(Serial.available() > 0) {
    charIn =(char) Serial.read();
    if (charIn == '1') {
      digitalWrite(led,HIGH);
      delay(5000);
      digitalWrite(led,LOW);
    }
  }
}

Python 代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from serial import Serial

ser = Serial('/dev/ttyUSB0', 9600)
x=ser.readline()
ser.write('1')
print(x)
def cleanup( str ):
  result = ""

  for c in str:
    if( (c >= "0") and (c <= "9") ):
       result += c

  return result

print( cleanup(x))
#ser.write("1") 
sensorValue = analogRead(sensorPin); //Reads the voltage of the resistor.
Serial.println(sensorValue); //Writes the voltage on the Serial port.
}

【问题讨论】:

    标签: usb arduino communication


    【解决方案1】:

    首先,您在 Python 代码中使用 Arduino 代码。

    sensorValue = analogRead(sensorPin); //Reads the voltage of the resistor.
    Serial.println(sensorValue); //Writes the voltage on the Serial port.
    

    您的计算机如何知道您的 Arduino 上的值是什么?您需要将其移动到 Arduino 代码中。我不能告诉你在哪里:你从来没有明确指定你想用这段代码完成什么。


    您的代码还有一些问题:

    • #ser.write("1") 应该是 ser.write("1")
    • 这两行还不错,但它们是一种不好的编码实践,因为您不使用它们: long previousMillis = 0;

      long interval = 1000;


    但 python 有时会收到 024、24 或 4 而不是 1024。

    Arduino 从不发送任何东西;没有serial.print();serial.println();!我不知道你是如何接收数据的。如果您对上面的代码进行了编辑和/或指定确切您想要做什么(即向 Arduino 发送 1,打开 LED,每五秒获取一次传感器数据, 如果数据超过 50%,请关灯) 仍然不知道该怎么办,欢迎评论澄清。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-27
      • 2019-05-27
      • 2019-09-01
      • 2018-04-16
      相关资源
      最近更新 更多