Arduino与Raspberry Pi的USB通信
我有一个通过USB连接的Arduino和一个覆盆子Pi。Python程序通过USB发送一个值,然后arduino接收该值并打开LED。Arduino正在将模拟值从A0发送到Raspberry上的Python程序。但是Python有时接收Arduino与Raspberry Pi的USB通信,usb,arduino,communication,Usb,Arduino,Communication,我有一个通过USB连接的Arduino和一个覆盆子Pi。Python程序通过USB发送一个值,然后arduino接收该值并打开LED。Arduino正在将模拟值从A0发送到Raspberry上的Python程序。但是Python有时接收024、24或4而不是1024。我怎样才能解决这个问题?这是我的密码: Arduino代码: int led = 13; char charIn; int sensorPin = A0; // select the input pin for the
024
、24
或4
而不是1024
。我怎样才能解决这个问题?这是我的密码:
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.
}
#/usr/bin/python
#-*-编码:utf-8-*-
从串行导入串行
ser=串行('/dev/ttyUSB0',9600)
x=ser.readline()
ser.write('1')
打印(x)
def清理(str):
result=“”
对于str中的c:
如果((c>=“0”)和(c作为初学者,则在Python代码中使用的是Arduino代码。
您的计算机如何知道您的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%,请关闭指示灯),但仍不知道该怎么办,请随时发表评论以获得澄清
sensorValue = analogRead(sensorPin); //Reads the voltage of the resistor.
Serial.println(sensorValue); //Writes the voltage on the Serial port.