简体   繁体   中英

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)

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 (ie a 16 bit signed value in "standard size" mode); if instead for some reason your device sends data in big endian, write > instead of < .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM