How do I make an "if" statement with serial data?

479 Views Asked by At

I am writing a python script that will gather data from a serial port. I am able to gather the data and when it comes out it says b'1' I want to make an if statement for if it comes out as b'1' then I want it to run a function.

This is my code.

import serial
import time
z1baudrate = 115200
z1port = '/dev/ttyACM0'

z1serial = serial.Serial(port=z1port, baudrate=z1baudrate)
z1serial.timeout = 2

print (z1serial.is_open)
if z1serial.is_open:
    while True:
        size = z1serial.inWaiting()
        if size:
            data = z1serial.read(size)
            print (data)
        else:
            print ("no data")
        time.sleep(1)
else:
    print("z1serial not open")

What should I do?

1

There are 1 best solutions below

1
On BEST ANSWER

You can use "==" operator with bytes.

if z1serial.is_open == b'1':
    ...

should do the trick.