PySerial - Full-duplex communication
Yes serial port hardware is full duplex. Yes, you can use threads to do Rx and Tx at the same time. Alternatively, you can use a single thread loop that does reads with a short timeout and alternates between reading and writing.
stephenfin
Updated on July 05, 2022Comments
-
stephenfin almost 2 years
Is it possible to achieve full-duplex communication using PySerial? Specifically, would it be possible to monitor the port continuously for input and write whenever needed? I imagine it should be possible using threads (and serial interfaces are full duplex no?). If not, what would be the best approach to monitoring a serial port when not transmitting? A timeout?
Edit: Here's my attempt at it. This code is targeting TI's CC2540 Bluetooth LE chip. On sending the GATT init message I expect a reply (detailing the operating parameters of the chip)...I'm getting nothing though
import serial import threading from time import sleep serial_port = serial.Serial() GAP_DeviceInit = \ "\x01\x00\xfe\x26\x08\x03\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00" def read(): while True: data = serial_port.read(9999); if len(data) > 0: print 'Got:', data sleep(0.5) print 'not blocked' def main(): serial_port.baudrate = 57600 serial_port.port = '/dev/ttyACM0' serial_port.timeout = 0 if serial_port.isOpen(): serial_port.close() serial_port.open() t1 = threading.Thread(target=read, args=()) while True: try: command = raw_input('Enter a command to send to the Keyfob: \n\t') if (command == "1"): serial_port.write(message) except KeyboardInterrupt: break serial_port.close()
-
stephenfin over 11 yearsCould you give a short example? Or perhaps indicate any immediate issues with the code sample given. The problem with the second approach is that I don't know when the data will need to be sent...the user will can choose what message to send at any time