Skip to content Skip to sidebar Skip to footer

Python Serial Communication

I'm working on an Arduino project, and I am interfacing it with a Python script due to memory limitations. On the Python side I have a 2 dimensional matrix containing respective x,

Solution 1:

You should wait a bit for the serial data to arrive.

The Arduino code should be:

if (Serial.available()){
    delay(100); // Wait for all data.while (Serial.available()) {
        char d = Serial.read();
        str.concat(d);
    }
}

Also you have to clear your string before re-using it.

[Edit]

I forgot to mention ÿ == -1 == 255 which means Serial.read() it is saying it can't read anything.

Solution 2:

I would change the communication so python sends newlines between numbers, so you're not as dependent on the timing:

s.write(str(25)+'\n')

and then on the receiving side:

voidloop(){
    while (Serial.available() > 0) {
        char d = Serial.read();
        if (d == '\n') {
            char t[str.length()+1];
            str.toCharArray(t, (sizeof(t)));
            int intdata = atoi(t);
            Serial.print(intdata);
            str = String();
        }
        else {
            str.concat(d);
        }
    }
}

Post a Comment for "Python Serial Communication"