0

I have a fixed message protocol to work with for a COM device. How do I

specifically declare that I do not have a termination character when I write to the serial port?

If I declare that I do not have any termination character from the serial port, is it necessary to specify that in the Serial.readline() as well?

    import serial
    ser = serial.Serial(
    port='COM4',
    baudrate=115200,
    parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE,
    bytesize=serial.EIGHTBITS,
    timeout=None,
    xonxoff=False, 
    rtscts=False, 
    write_timeout=None, 
    dsrdtr=False,
    inter_byte_timeout=None, 
    exclusive=None)
Rene Duchamp
  • 2,429
  • 2
  • 21
  • 29
  • When you say fixed message I'm guessing you mean fixed-length. If so, how does it make sense to use `readline? Maybe there's a hidden angle I'm missing. In any case, take a look [here](https://stackoverflow.com/questions/10222788/line-buffered-serial-input), maybe it helps. – Marcos G. Jul 26 '19 at 15:00
  • @MarcosG. yes, fixed length. This is my first attempt with PySerial. If not for readline, then is there another way to read all bytes from the port? – Rene Duchamp Jul 26 '19 at 15:06
  • yes, see below, I hope it helps. – Marcos G. Jul 26 '19 at 15:32

1 Answers1

1

If you don't have a line termination character and your message is of fixed length it makes more sense to read a fixed number of bytes from the port.

If, for instance, your message is 100 bytes you can do:

serial.read(100)     # Reads UP TO 100 bytes

Note that if you have a None timeout this will read up to 100 bytes. So if you have less than that it will return as many as it found (that might be 99, 5, or none).

With this in mind, it is recommended that you check you received the complete message by comparing the number of bytes received with the expected message length.

You can also define a timeout with timeout=1 and do something like this:

timeout=time.time()+3.0
while ser.inWaiting() or time.time()-timeout<0.0:
    if ser.inWaiting()>0:
        data+=ser.read(ser.inWaiting())
        timeout=time.time()+3.0
print(data)

This will make sure you read the whole message and nothing else has been arrived to the buffer by waiting for 3 seconds after you finish reading.

Marcos G.
  • 3,371
  • 2
  • 8
  • 16