python and serial. how to send a message and receive an answer

前端 未结 4 1853
清歌不尽
清歌不尽 2021-01-22 13:05

I have to send ZANE:1:00004:XX_X.X_XXXX_000XX:\\r\\nvia serial communication with python.

here is my code:

import serial
ser = serial.Seria         


        
4条回答
  •  清歌不尽
    2021-01-22 13:17

    I believe the earlier answers didn't understand that you are using the same port for writing and reading.

    I'm having the same problem and solved it using a sleep function. Basically:

    import serial
    from time import sleep
    ser = serial.Serial('/dev/cu.usbserial-A901HOQC', timeout=1)
    ser.baudrate = 57600
    
    msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
    ser.write(msg)
    sleep(0.5)
    ser.readline()
    

    So with that sleep you are giving time to the receiver (a machine?) to send the reply. Also note that you have to add a timeout if you want to use readline.

提交回复
热议问题