Function triggered when data comes to serial port in python

Copper Contributor

I am checking the incoming data by reading continuously in while true in a separate thread. I don't want it to work constantly. Is there a function that will only be triggered when data arrives in  python?

https://bit.ly/3iZ3cZD

my code:

import threadingimport serial

connected = Falseport = "COM3"baud = 115200serial_port = serial.Serial(port, baud, timeout=0)

def handle_data(data):
    print(data)

def read_from_port(ser):        select_read(serial_port)        serin = ser.read()        connected = True

        while True:           reading = serial_port.in_waiting
           reading = ser.readline().decode()
           if len(reading) > 5:       
                handle_data(reading)


def set_data():
    while True:
        print("input: ")        num1 = str(input())        serial_port.write(num1.encode());thread = threading.Thread(target=read_from_port, args=(serial_port,))thread2 = threading.Thread(target=set_data)thread.start()thread2.start()
0 Replies