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

前端 未结 4 1851
清歌不尽
清歌不尽 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.

    0 讨论(0)
  • 2021-01-22 13:28

    In order to read you need to open a listening port(with a timeout) first, for example:

    ser = serial.Serial('/dev/cu.usbserial-A901HOQC', 19200, timeout=5)
    x = ser.read()          # read one byte
    s = ser.read(10)        # read up to ten bytes (timeout)
    line = ser.readline()   # read a '\n' terminated line
    ser.close()
    

    See more details here.

    0 讨论(0)
  • 2021-01-22 13:40

    Here two thinks are important.first one is timeout and second one is EOL charector.. if you are going to use time out in the receiver side then no need EOL from transmitter side. if you are going to use EOL charector in transmitter side(/n,/r) then no need to put time out in the receiver side. Ex: serialport=serial.serial(port,baud,timeout) if you are going to use time out incoming signal over serial port(Ex: hello how are you? nice to meet you man!!) Here new line cherector does not respond well.so you can leave it.

    Ex: serialport=Serial.serial(port,baud) if you are not going to put time out in serial port then you should use end of line charector(/n,/r) in the transmitter Note : Second way is more efficient than first way

    0 讨论(0)
  • 2021-01-22 13:41

    Your device is probably not terminating its response with a newline character. the .readline() method is expecting a newline terminated string. See here: http://pyserial.sourceforge.net/shortintro.html#readline for more info.

    try setting a timeout on your serial connection

    ser.timeout = 10
    

    and replace the ser.readline() with ser.read(n) where n is the number of characters you wish to read. ser.read(100) will try to read 100 characters. If 100 characters don't arrive within 10 seconds, it will give up and return whatever it has received.

    0 讨论(0)
提交回复
热议问题