Skip to content Skip to sidebar Skip to footer

Clash Of Connection Between Serial Port Read And Write Codes

This is the code that reads from the z1 mote while True: if not ser.isOpen(): try: ser = serial.Serial(z1port, z1baudrate,timeout=0, parity=serial.PARITY_NONE,

Solution 1:

You can only create one serial connection to a device. The code in your question creates two connections, one in the main routine and one in the subroutine. In the main routine, you create a connection to establish communication with the device:

ser = serial.Serial(z1port, z1baudrate) # I assume z1port='/dev/ttyUSB1'

Then in your subroutine you also create a connection:

ser = serial.Serial("/dev/ttyUSB1")

So there are now two connections trying to use the same port. This will not work.

Instead, you should use the original connection throughout your program, and define your subroutines to receive the connection as an input parameter. For example:

ser = serial.Serial(z1port, z1baudrate)
# do whatever to make connection to the device
getMessage(ser) # call subroutine to read data *with the existing connection*
ser.close()     # close connection when finisheddefgetMessage(serConn):
  # read data
  data = serConn.read(1000)
  # send ack
  serConn.write(b'OK')

Another option is to open and close serial connections throughout your code, whenever you need to do communication. This is usually much less efficient, and only makes sense if there will only be intermittent communication with the device.

Solution 2:

I used the idea by @mhopeng to write a code that implements multithreading programming, where one function handles the reading and the other handles the writing. And before they are both called, I will connect to the serial port and pass it to both of the threads.

I had to use multithreading because I needed a separate thread for writing at any time from the user input.

Post a Comment for "Clash Of Connection Between Serial Port Read And Write Codes"