Problem with struct-lib


#1

Hey!

I try to communicate with an EEPROM using an F&C SAM3X. The device I try to read is configured to wait for incoming bytes. First byte is the command, the second byte is the position to read. As I have several positions to read I use integers in the program to indicate the position I want to read. Therefore I have to convert this integer into a byte to send it to the EEPROM. My program looks like this:

def _send(ser, cmd, pos = None, discard_resp = False):

try:
    pos = struct.pack('b', pos)
except Exception as e:
    print('Did not work: ', e)

try:
    digitalWrite(settings.pin_RS, HIGH)
    ser.write(cmd)
    ser.write(pos)
    return _read(ser,260)
except Exception as e:
    print(e)

calling the function with pos=2 and listening to my RS-interface with my laptop leads to the following results:
the command is written correctly.
the position is written as 0x82 instead of 0x02

I tried the same function using the python installed on my laptop and there the conversion workes.
Did I miss something in the description in the lib or why is the first bit after the struct.pack inverted?

Thanks in advance for your help!

Max


#2

Hi @Max,

I’ve tried to replicate your scenario with a minimal working example:

import streams
import struct

mser = streams.serial()

pos = 2
pos = struct.pack('b', pos)
while True:
    mser.write(pos)
    sleep(1000)

First of all, am I right in supposing that this can be your case reduced to the bare minimum? :slight_smile:
Then I tried listening to its output on a serial port (script running on my pc):

import serial
ser = serial.Serial('/dev/ttyACM0', baudrate=115200) 
while True:
    print(ser.read(1)) 

and the output I get is the expected one:

b'\x02'
b'\x02'
b'\x02'
b'\x02'

So the struct library seems to work correctly, let me know if I did not get your issue properly or feel free to share more details about your project and your overall code (even via private message) :+1: