1
votes

Problem 1: I'm trying to read serial data coming from my arduino using pySerial. Sometimes the code seems to work well but sometimes it prints strange things. The arduino monitor always prints the normal data, the strange behavior just happens on the python code.

Another thing: this just happens when I increase the baudrate from 9600 to 115200, but I really need this higher baudrate.

Output example:

Opening COM port...
Port successfully opened
b'7\r\n'
b'133\r\n'
b'125\r\n'
b'114\r\n'
b'104\r\n'
(...) (and suddenly here comes again)
b'\xbaj\xea2\x93j\n'
b'\xa6\x13j\n'
b'&\x13j\n'
b'&\x93j\n'
b'\xa6\xd3j\n'
(...)
[Finished in 2.0s]

Sometimes I need to cancel the build because it gets stuck in the for loop.

Problem 2: Besides that, after reading the data I need to convert it to int. Just tried "int(data)" but obviously It didn't worked. Certainly because of the Problem 1.

When I change this:

print(data)  

To this:

print(int(data))  

I get this:

ValueError: invalid literal for int() with base 10: b'\xa1j\n'

Python Code:

import serial

print("Opening COM port...")

# open and prepare serial port
ser = serial.Serial('COM3', 115200, timeout=8,
                    parity=serial.PARITY_EVEN, rtscts=1)

print("Port successfully opened")

for i in range(50):
    data = ser.readline()
    print(data) # print(int(data))  

ser.close()

Arduino Code:

void setup() {
    Serial.begin(115200); // set baudrate
}

void loop() {
    int data = 0;
    int analogPin = 1;

    data = analogRead(analogPin); // read pin
    Serial.println(data, DEC); // print data to the serial port

}
1

1 Answers

0
votes

Data validity suffers at higher data transfer speeds because the hardware can't read the data sent in the right sequence. Try lowering your baudrate to 57600.