Kevin
Kevin

Reputation: 561

Continuous data streaming from Arduino to Python (failing readlines)

I'm trying to continuously read data off of my Arduino Nano via a Python script. But most of the time, the readline would either fail throwing an exception or return corrupted data, like missing a digit.

Here's the connection part:

The Arduino code:

void loop() {
    // Send data only when you receive data:
    if (Serial.available() > 0) {

        // Check if it's the right signal.
        if (Serial.read()=='S') {
            // Send a string containing the rows and cols number.
            send_rows_cols();

        } // if(Serial.read()=='S')
        else {
            send_data();
        } // END: else if( Serial.read()=='Y')
    }// if(Serial.available() > 0)
}

In the send_rows_cols(), I'm using Serial.write, because it works but in send_data() I had to use Serial.println() to send the data back.

The Python part. Here's the ridiculous run around way I had to use until legitimate values were returned.

import serial
import time

locations=['/dev/ttyUSB0','/dev/ttyUSB1','/dev/ttyUSB2','/dev/ttyUSB3',
'/dev/ttyS0','/dev/ttyS1','/dev/ttyS2','/dev/ttyS3']

for device in locations:
    try:
        print "Trying...",device
        arduino = serial.Serial(device, 9600)
        break
    except:
        print "Failed to connect on",device

rows_cols =''

try:

    while True:
        arduino.write('S')
        rows_cols = str(arduino.readline())
        print len(rows_cols)
        print rows_cols
        if ( len(rows_cols)>3 ):
            break

except:
    print "Failed to send!"

Up to this point it works after one or two readlines. Which is affordable. Later though, I had to use even crazier code. Sending a character from Python to Arduino so the connection wouldn't die, then as you can see the Arduino has to wait for that character. After the Arduino receives that character it sends back the data that I want (a string of numbers separated with commas).

This last Python part is what it sends the 'Y' char and readline from the Arduino, again and again until there's no exception or corrupt data. So many loops for nothing.

What I would like is a way to get continuously data off my Arduino without having that "handshake" all the time and that data to not be garbage all the time.

Is there such a way? Maybe a timeout option for the Serial?

Upvotes: 4

Views: 7928

Answers (1)

Martin Thompson
Martin Thompson

Reputation: 16792

You've not got the Arduino IDE Serial Monitor open as well have you? I spent a "happy" evening debugging my "Python to Arduino interface code" before I realised I'd left that open and it was eating occasional characters :)

I've certainly used very simple Serial.write() and Serial.println() code along with readline() to run continuous "command/response" testing for many tens of minutes at a time (many thousands of lines of sends and receives)

Upvotes: 4

Related Questions