Dec-27-2021, 02:45 AM
I'm new to Python but serial is of great interest to me. I have an app built that relies on a serial connection and this is how I handled it, it works well.
The following snippet is the basis for receiving. As BashBedlam notes you will need the pyserial module, if you happen to have other serial modules installed it can give you problems, it did for me so I ended up uninstalling them all and reinstalling pyserial.
This code runs in a while loop and constantly monitors the serial port for incoming data, the readline() reads a string until it meets a newline character, the strip() removes the unwanted newline or carriage return and then the string is printed in the output panel. When you use this in an application you will want to run the while loop in a separate thread. When you are comfortable with whats happening you can go onto identifying ports and selecting them via an interface.
The following snippet is the basis for receiving. As BashBedlam notes you will need the pyserial module, if you happen to have other serial modules installed it can give you problems, it did for me so I ended up uninstalling them all and reinstalling pyserial.
This code runs in a while loop and constantly monitors the serial port for incoming data, the readline() reads a string until it meets a newline character, the strip() removes the unwanted newline or carriage return and then the string is printed in the output panel. When you use this in an application you will want to run the while loop in a separate thread. When you are comfortable with whats happening you can go onto identifying ports and selecting them via an interface.
import serial ser=serial.Serial("COM7",9600) ser.reset_input_buffer() while True: if ser.isOpen(): input_string=ser.readline().strip().decode("utf-8") print(input_string)Sending strings is just as easy
def output_string(): if ser.isOpen(): ser.write("Some string here".encode("utf-8"))