Trouble with PySerial read

1.1k views Asked by At

I'm trying to read data from an Arduino serial monitor, but I'm having problems with pyserial's readline function. Here's the simple code which prints to the monitor:

void setup() {
  Serial.begin(19200);
}

void loop() {
  Serial.print("helloWorld");
  delay(1);        // delay in between reads for stability
}

And here's the Python code I'm using to read the printed output:

import serial
arduinoSerialData = serial.Serial()
arduinoSerialData.port = "COM4"
arduinoSerialData.baudrate = 19200
arduinoSerialData.timeout = 1
arduinoSerialData.setDTR(False)
#arduinoSerialData.setRTS(False)
arduinoSerialData.open()
while(True):
    b = arduinoSerialData.readline().decode('utf-8').strip().split(',')
    print(b)


This is the error:

  File "SerialRead.py", line 11, in <module>
    str_b = b.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x91 in position 7: invalid start byte

I have no clue what could be going wrong. Does anyone have any suggestions? Thank you for your time!

1

There are 1 answers

0
Domkrt On

I have this code, and this is perfect:

import serial

Ser=serial.Serial(port='com8',baudrate='9600',timeout=1)

while True:
    print(Ser.readline())

Convert this data to string, and remove uneccesary character. Example:

import serial

Ser=serial.Serial(port='com8',baudrate='9600',timeout=1)

while True:
    data=Ser.readline()
    data=str(data)
    try:
        dat1=data.replace("b","")
        dat2=dat1.replace("\r\n","")
        dat3=dat2[:-5]
        dat4=dat3.replace("'", "")
        print(dat4)
    except:
        print("ERROR: replace method error")

Good luck!