Python Forum

Full Version: serial input/output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I want to use a joystick to control a RS-232 controlled telescope. I have installed PyGame and have the joystick working. Now, I want to send a serial ascii text string via RS-232 to my telescope depending on my joystick movements. So, I need to know how to use python to send and receive text characters to my scope via a USB port configured for serial communication. I was hoping that PyGame might have something like this but I have not found it as yet.

Stand alone Terminal programs like PUTTY will do this task but I want to integrate my telescope commands into my python program. Sp, I need a function to send a text string, a function to detect if there is a message to read, and then a function to read and display the message.
There is a module calledpyserialthat you can install with pip. I have no way of testing it but perhaps you can find information on it now that you have a name to search for.
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.

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"))
It seems to run but I will have to make a "wrapper" program to test it thoroughly.
It took a while to get it going as I had to wade through Windows security and access permissions so I could load Pyserial.