I was trying to communicate between an Arduino and Python 3 running on my laptop. The Arduino was supposed to receive 0x30
, i.e. an ASCII 0
and reply with ASCII "Arduino reachable."
(see the code at the end). The Python code was as simple as it gets:
import serial, time
ports=['/dev/ttyACM0']
fixture = serial.Serial(port=ports[0],baudrate=9600,timeout=2,stopbits=sm.serial.STOPBITS_ONE,parity=sm.serial.PARITY_EVEN,bytesize=sm.serial.EIGHTBITS)
fixture.write(b'0')
time.sleep(0.1)
if (fixture.inWaiting() > 0):
dataStr = port.read(fixture.inWaiting())
print(dataStr)
fixture.close()
The Arduino was replying, but the reply didn't make much sense: 'A.V¥n\x0b\x92\x95a,+\x89lY©'
. In the end, I've changed parity
to serial.PARITY_NONE
and that worked like a dream.
Also, I suggest the following method of waiting for the data to appear:
TIMEOUT = 20
timeoutCounter=0
while fixture.inWaiting() <= 0: # Wait for data to appear.
time.sleep(0.1)
timeoutCounter += 1
if timeoutCounter == TIMEOUT:
fixture.close()
raise BaseException('Getting test data from the Arduino timed out.')
Related Arduino code
void setup()
{
Serial.begin(9600);
}
void loop()
{
char cmdChar = '0'; // Which test case to execute. 0 - do nothing.
// Wait until there is something in the serial port to read.
if (Serial.available() > 0)
{
// Read the incoming serial data.
cmdChar = Serial.read();
// Eexecute the chosen test case.
switch(cmdChar)
{
case '0':
Serial.print("Arduino reachable."); // Send ASCII characters.
break;
}
}
}
Caveat
I'm sorry but I've had to edit this code before posting, and haven't had a chance to re-test it. However, the main solutions to errors like reported in the questions still hold:
- Wrong parity (probably stop bits also),
- Insufficient waiting for the data to appear (possibly not the cause of the problem but definitely a bad practice).