I'm working on project where python sends motor commands to an Arduino Mega via USB. I have been playing with several variations of how to make the code robust so that the python program waits until the arduino is ready to receive. This is a super basic version for the question.
What is wrong is that the arduino println is sending the value back successfully to be read in the serial monitor in the arduino IDE. But the python is not reading it successfully to print a value to the command line.
What is wrong with my python read code?
Arduino
//++++++++++++++++++++Initializations+++++++++++++++++++++
int command = 0;
int control = 0;
boolean newInput = 0;
int myCount = 0;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void setup() {
Serial.begin(9600); // set the baud rate
Serial.println(1); // initial "ready" signal
}
void loop() {
// read sent command and return it
if(Serial.available() > 0){ // only send data back if data has been sent
command = Serial.read();
delay(10);
Serial.println(1); // send "ready" signal
delay (50); //alternatively Serial.flush();
myCount++;
}
}
Here is the condensed version of my program that highlights the issue.
Python
import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1)
import time
controlBit = True
n = 0
charsWait = 0 #chars waiting from arduino
print "Starting up"
connected = False
while True:
n = n+1
print n
print "Writing"
ser.write(str(2))
time.sleep(1)
while True:
try:
print "reading"
charsWait = ser.readline()
time.sleep(1)
print " = value recieved", charsWait
break
except:
pass
print "restart"
ser.flush() #flush the buffer