1

I want to react to a serial input with this simple Python script:

import serial

ser = serial.Serial('COM7', baudrate=9600, timeout=1)

while True:
    data = ser.readline().rstrip()
    print(data)
    if (data == 'ON'):
        print("I received: ON")

I run this script on my pc with an Arduino connected to COM7. Its code looks like this:

void setup() {
  Serial.begin(9600);
}
void loop() {
  Serial.println("ON");
  delay(500);
}

The cmd outputs this:

b'ON'
b'ON'
b'ON'
b'ON'

As you can see the serial communication is ok and the computer receives the data, but how can I check for a certain word or a certain number? What's my mistake?

Thank you in advance.

And yes I know, that there's a question with the same title out there, but it didn't work for me.

0buz
  • 3,443
  • 2
  • 8
  • 29
Michael Brown
  • 137
  • 2
  • 13
  • you are getting string in binary format you need to convert it this may help https://stackoverflow.com/questions/17615414/how-to-convert-binary-string-to-normal-string-in-python3 – deadshot Jun 22 '20 at 10:32

1 Answers1

0

As you can see from your output, the data you receive is bytes (note the b at the beginning).

You must decode it to a string:

data = data.decode('utf8')  # or any other encoding used by the data source

then you can compare it to any string.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50