Clash of connection between serial port read and write codes

随声附和 提交于 2019-12-25 04:32:01

问题


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?


回答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 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.




回答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.



来源:https://stackoverflow.com/questions/36222823/clash-of-connection-between-serial-port-read-and-write-codes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!