Ahmed Al-haddad
Ahmed Al-haddad

Reputation: 833

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, 

                    stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
      except:
        sys.exit("Error connecting device")

   queue = ser.inWaiting()
   if queue > 0:
      data = ser.read(1000)
      print data 
   time.sleep(0.2)

And this is the code that I have that I use it to write to the mote

# some event-driven code here so that whenever a message is received then do: 
print(str(msg.payload))
ser = serial.Serial("/dev/ttyUSB1")
print ser.isOpen()
ser.write(msg.payload)

The output from the second code should be if msg.payload = "hello":

hello 
True 

But then the read code stops reading from the serial port (the code will run but no input). How do I solve this problem?

Upvotes: 0

Views: 370

Answers (2)

Ahmed Al-haddad
Ahmed Al-haddad

Reputation: 833

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.

Upvotes: 0

mhopeng
mhopeng

Reputation: 1081

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 finished

def getMessage(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.

Upvotes: 1

Related Questions