Arduino和Raspberry Pi之间通过USB的通信

问题描述 投票:0回答:1

我有一个通过Raspberry Pi通过USB连接的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个回答
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(); ! 我不知道您如何接收数据。 如果您编辑自己的代码上面和/或指定你想要做什么 (即发送1到Arduino,打开一个LED上,获得传感器数据传回每五秒钟,如果数据是50%以上,转熄灭 ),但仍然不知道该怎么做,请随时发表评论以进行澄清。

© www.soinside.com 2019 - 2024. All rights reserved.