【发布时间】:2016-03-26 04:53:03
【问题描述】:
我有一个 python 脚本,可以通过串口与 arduino 通信。它在我的计算机上按预期工作,但是当我在 Raspberry Pi 上运行脚本时,它不起作用。打印“Sent: 1”后卡住了。我认为它一直在等待来自 arduino 的一个字节(来自 sendValue 的第一行)。但是,我不知道为什么会这样,因为它可以从我的计算机或 Pi 的串行监视器上正常运行。
Python 脚本:
import serial
ser = serial.Serial('/dev/ttyACM0', 9600)
def sendValue(value):
ser.read(1) # Arduino will send one byte when it's ready for the value
ser.write(value) # Send value
print("Sent: {}".format(value))
return;
ser.write('1') # Select function '1'
print("Sent: 1")
sendValue('5000') # Send 1st parameter to function '1'
sendValue('4000') # Send 2nd parameter to function '1'
while True:
print(ser.readline())
Arduino 代码:
int task = 0;
int val = 0;
int val2 = 0;
int val3 = 0;
void task1(int length){
Serial.println(length);
digitalWrite(13, HIGH);
delay(length);
digitalWrite(13, LOW);
}
void task2(int length1, int length2){
Serial.print("Running task2 with parameters ");
Serial.print(length1);
Serial.print(" and ");
Serial.println(length2);
digitalWrite(13, HIGH);
delay(length1);
digitalWrite(13, LOW);
delay(500);
digitalWrite(13, HIGH);
delay(length2);
digitalWrite(13, LOW);
}
void waitForSerial(){
while(Serial.available() == 0);
}
int getValue(){
Serial.write(48);
waitForSerial();
return Serial.parseInt();
}
int getCommand(){
if(Serial.available() == 0){
return -1;
}
String in = "";
in += (char)Serial.read();
return in.toInt();
}
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop() {
task = getCommand();
switch(task){
case 0:
val = getValue();
task1(val);
val = 0;
break;
case 1:
val = getValue();
val2 = getValue();
task2(val, val2);
val = val2 = 0;
break;
}
}
我尝试过延迟而不是 ser.read(1),我认为它会卡住但仍然不起作用。
我无法决定是将它放在 Raspberry Pi 社区还是 Arduino 社区,所以我把它放在这里。
【问题讨论】:
标签: python arduino raspberry-pi arduino-uno