Snap7 get_real command not working, how to fix?

660 Views Asked by At

client = snap.client.Client()
client.connect('XXX.XXX.X.XXX', 0, 2)  #IP address, rack, slot

db = client.db_get(20)
print(db)

intDB = []

for i in range(1, 122):
    reading = client.db_read(20, i, 1)
    realReading = snap.util.get_real(reading, 0)
    array = [realReading]
    intDB.append(array)

print(intDB)

This code is supposed to print a DB in bytearrays and then print an array with the floats values of the PLC output. However, when I run the code, I get the following error message:

Traceback (most recent call last):
  File "C:/Users/Asus/PycharmProjects/PLC-Connection/main.py", line 19, in <module>
    realReading = snap.util.get_real(reading, 0)
  File "C:\Users\Asus\PycharmProjects\PLC-Connection\venv\lib\site-packages\snap7\util.py", line 357, in get_real
    real = struct.unpack('>f', struct.pack('4B', *x))[0]
struct.error: pack expected 4 items for packing (got 1)
1

There are 1 best solutions below

0
On

I think that the problem is reading the data:

reading = client.db_read(20, i, 1)

20 is the datablock, i is the index, and you read only 1 byte (3rd parameter).

For retrieving a real, you need 4 bytes read out.