Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
serial input/output
#3
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"))
BashBedlam likes this post
Reply


Messages In This Thread
serial input/output - by barryjo - Dec-27-2021, 01:16 AM
RE: serial input/output - by BashBedlam - Dec-27-2021, 01:42 AM
RE: serial input/output - by Jeff_t - Dec-27-2021, 02:45 AM
RE: serial input/output - by barryjo - Dec-27-2021, 11:57 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Waiting for input from serial port, then move on KenHorse 3 1,323 Apr-17-2024, 07:21 AM
Last Post: DeaD_EyE
  pyserial/serial "has no attribute 'Serial' " gowb0w 9 5,236 Aug-24-2023, 07:56 AM
Last Post: gowb0w
  output provide the filename along with the input file processed. arjunaram 1 993 Apr-13-2023, 08:15 PM
Last Post: menator01
  How to input & output parameters from command line argument shantanu97 1 2,640 Apr-13-2021, 02:12 PM
Last Post: Larz60+
  Code giving same output no matter the input. Yort 2 2,664 Dec-20-2020, 05:59 AM
Last Post: buran
  Handling multi-input/output audio in python bor1904 4 3,685 Nov-04-2020, 08:25 AM
Last Post: CHLOVRL
  single input infinite output problem Chase91 2 2,023 Sep-23-2020, 10:01 PM
Last Post: Chase91
  My code is giving my an output of zero, no matter what value I input PiyushBanarjee 1 1,955 Jul-01-2020, 04:34 AM
Last Post: bowlofred
  Help me input the Rawdata file so that it can output DataErrorFile and ValidData.txt Halozeus 6 3,314 May-01-2020, 07:11 AM
Last Post: bowlofred
  ınput-output HELP! bwdu 1 2,018 Apr-18-2020, 09:53 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020