I have a python script that communicates with an arduino over serial. It works as expected on my computer but when I run the script on my Raspberry Pi, it does not work. It gets stuck after printing "Sent: 1". I think it is stuck waiting for one byte from the arduino (first line from sendValue). However, I don't know why this is happening as it works fine running it from my computer or the Pi's serial monitor.
Python script:
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 code:
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;
}
}
I have tried putting a delay in instead of the ser.read(1) where I think it is getting stuck but that still doesn't work.
I could not decide whether to put this on the Raspberry Pi community or Arduino community so I put it here.