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

15,113

Solution 1

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.

Solution 2

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.

Solution 3

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.

Share:
15,113
otmezger
Author by

otmezger

Basking.io

Updated on June 04, 2022

Comments

  • otmezger
    otmezger almost 2 years

    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.Serial('/dev/cu.usbserial-A901HOQC')
    ser.baudrate = 57600
    
    msg = 'ZANE:1:00004:XX_X.X_XXXX_000XX:\r\n'
    

    If I write:

    >>> ser.write(msg)
    

    the answer will be 33, which is the length in byte of the message I'm sending.

    How can I receive the answer? The connected device will answer just after he gets the message, but if I type

    >>> ser.write(msg); ser.readline()
    

    the result will be that readline never gets any message at all...

    any ideas?