1

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.

1
  • 1
    maybe you can explain what exactly you are trying to do with your code. It is probably very clear to you but I think anyone else won't have a clue. You need to take into account the speed at which you are sending and receiving data, otherwise you'll get those -1 values meaning there was nothing available to read on the port at the time you tried reading. Commented Dec 3, 2019 at 7:20

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.