I am very new to using serial ports, and I have a question I really couldn't solve. Let me explain the issue with the code I have been using.
The Python code:
from time import sleep
import serial
ser = serial.Serial('COM8', 9600)
incoming=[10,15]
while True:
ser.write((incoming))
msg=(ser.readline())
print(msg.decode('utf-8'))
sleep(3)
int incoming[3];
The arduino Code:
void setup() {
pinMode(13, OUTPUT);
Serial.begin(9600);
Serial.println("Ready");
}
void loop() {
if(Serial.available()) {
for (int i = 0; i < 3; i++) {
incoming[i] = Serial.read();
}
if (incoming[1]==-1){
Serial.println(incoming[0]);
Serial.println(incoming[1]);
Serial.println(incoming[2]);
Serial.println(incoming[3]);
}
}
When this runs(I first load the arduino code, then run the script from python) The code runs successfully but the output comes out like this; Ready 10 -1 -1 15 -1 -1 10
And so it goes on... Why do these -1 show up? I have searched on the internet but couldn't come up with anything that might solve the problem at all. I would appreciate any help on this issue. Thanks a lot.
Have a look at the Arduino Documentation.
The -1 from Serial.read()
means "no data available".
A little bit longer:
You are waiting until a character is available on the serial interface. After that you try to read 4 characters but nobody knows if they are already available. (The serial interface is not so fast, the µC is much faster) So you are read the "no character" two times before the next char from the Python script arrives.