I have got a question about serial communication between Arduino and Raspberry Pi. The fact is I want to send 2 variables to Raspberry Pi with Arduino and use them in different ways.
Here my sketch for Arduino :
int one = 1;
int two = 2;
void setup()
{
Serial.begin(9600);
}
void loop()
{
Serial.print(one);
Serial.print(two);
delay(3000);
}
Here my python script for Raspberry:
import serial
import time
ser = serial.Serial('/dev/ttyACM0', 9600)
time.sleep(4)
while True:
data=ser.read()
print data
The problem is that 'data' in the python code takes the two values send by Arduino (because of two print in the Arduino loop() ). But I want to receive the datas in Raspberry Pi with two different variables (to record them after). I try many technics to receive these datas in two different ways, but it not work.
Thank you for your help.
Arduino's
Serial.print
sends data as ASCII. So your commands from the Arduino actually send the string12
. There is no way for Python do see where the first value ends and where the second one begins.One solution is to use
Serial.println
instead ofSerial.print
. This will add a carriage return and a newline after each call. So the string will become1\r\n2\r\n
.On the Python side you can then use the
split
method. An example in IPython:And you can then easily convert the values to integers.
Note: it is possible for Python to get an incomplete message! So you just might receive the string
1
the first time you read and2
during a second read! So you might want to consider formatting your data so you know you have received a complete message.One option to do that is to format your data as JSON. In your example this would be
{"one": 1, "two": 2}
. In this simple calse you can check that you have received a complete message because it starts with a{
and ends with a}
. But you could also use Python's built-in JSON parser.Using the JSON parser has an advantage because it raises an exception when you try to parse an incomplete message:
The correct way to deal with this is to keep reading data from the serial port and appending it to a string until parsing the data doesn't fail;
Re,
In first I want to thank you for your answer and to make me discover Json. So I tried your last python code and modify my Arduino code like this :
In raspberry Py when i execute the code (without a while), the console return nothing. It seems that data send juste one character.
Thanks again