I am writing a program in python to communicate with arduino. My python program sends signed integers to arduino. x and y are to be sent from python and in arduino i want to retrieve them as it is like x and y separate variables. but so far I have succeded to retrieve data but it is being stored in single variable i.e. x=-13 but I want it like x=-1 and y=3. Could somebody please guide me a way to do it. Thanks
my arduino code:
String a; String b;
void setup() {
Serial.begin(9600);
// Serial.setTimeout(1);
Serial.println("start");
}
void loop() {
if(Serial.available()>0){
a=Serial.readString();
b=Serial.readString();
Serial.println(a);
Serial.println(b);
int x = a.toInt();
int y = b.toInt();
Serial.print("x=");
Serial.println(x);
Serial.print("y="); Serial.println(y);
}
}
python code:
import serial
import time
import math
ser = serial.Serial('COM1',9600,timeout=1)
time.sleep(1)
x="-1"
y="3"
print(ser.write(x.encode()))
print(ser.write(y.encode()))
If you modified the python code to include a newline after each variable then the following arduino code example should capture your data. In my example I have let the variables remain as strings, see if you can get the strings to display at you python program before you move on to converting to integers.
const unsigned int MAX_MESSAGE_LENGTH = 14;
//Create a place to hold the incoming message
static char message[MAX_MESSAGE_LENGTH];
static unsigned int message_pos = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
//Check to see if anything is available in the serial receive buffer
while (Serial.available() > 0)
{
//Read the next available byte in the serial receive buffer
char inByte = Serial.read();
//Message coming in (check not terminating character) and guard for over message size
if ( inByte != '\n' && (message_pos < MAX_MESSAGE_LENGTH - 1) )
{
//Add the incoming byte to our message
message[message_pos] = inByte;
message_pos++;
}
//Full message received...
else
{
//Add null character to string
message[message_pos] = '\0';
//Print the message (or do other things)
Serial.print("Message...");
Serial.println(message);
//Reset for the next message
message_pos = 0;
}
}
}