Garth Braithwaite
Garth Braithwaite

Reputation: 141

PySerial 16bit integer

I'm trying to interpret a signal from a relay unit that is sending 16bit integers over 9600bps using PySerial, and I can't figure out how to format the response.

The relay is supposed to be sending 257[var]257[var]... etc

This is what I'm doing to get the value; I just don't know how to format it to something useful:

import serial
with serial.Serial('/dev/ttyS0',9600,8,serial.PARITY_NONE,serial.STOPBITS_ONE) as ser:
  for i in range(10):
    val = ser.read(2)

Upvotes: 0

Views: 1234

Answers (1)

Matteo Italia
Matteo Italia

Reputation: 126787

You can use struct.unpack to convert binary data to Python values.

val = struct.unpack("<h", ser.read(2))[0]

where < means little endian, standard size values, and h means signed short int (i.e. a 16 bit signed value in "standard size" mode); if instead for some reason your device sends data in big endian, write > instead of <.

Upvotes: 1

Related Questions