Siemens S7-1500 control with Python snap7

451 views Asked by At

I want to connect to PLC S7-1500 with snap7 v1.3. I have notes from someone who has previously used the existing PLC with Matlab.

For motor start bool 'DB50 DBX 0.5'

status = connection.WriteValues({PlcBoolean('DB50.DBX 0.5',true) });

For reading the speed of motor real int 'DB50.DBD 2'

motor_speed = connection.ReadReal('DB50.DBD 2',20);

To move motor at given value

changingValue = event.Value;
value3 = PlcBoolean('DB50.DBX 0.5',true);  %motor movement command
app.connection.WriteValues({value3 });

After the motor start command is given to the PLC S7-1500, the Python code I gave below works, but I could not find how to give the start command.

import snap7
import struct
import threading

def update_speed_value():
    while True:
        changing_value = float(input("Value: "))
        value_bytes = bytearray(struct.pack('>f', changing_value))
        client.db_write(50, 2, value_bytes)

client = snap7.client.Client()
client.connect('192.168.0.1', 0, 1)

moving_value = True
client.db_write(50, 5, bytearray([1 if moving_value else 0]))

update_thread = threading.Thread(target=update_speed_value)
update_thread.daemon = True
update_thread.start()

try:
    while True:
        pass
except KeyboardInterrupt:
    pass

client.disconnect()

Could you help me about this?

1

There are 1 answers

0
Martin Čičmanec On

according to your python code, you are writing the boolean into DB50 and into the fifth byte inside that DB. You are writing the data bytearray([1]) which is respresented as bytearray(b'\x01') This means you write True value into the first bit inside the fifth byte of DB50. Are you sure this is the correct bit address?

'DB50.DBD 2' means the speed float value starts after the second byte in DB50.

'DB50.DBX 0.5' means the first (zero index) byte and the fifth bit inside it.

Snap7 has a very useful util module for delaing with conversions. I would do it like this:

start_byte = client.db_read(50, 0, 1) # Read first byte
# For reading the bool from byte
start_bit = snap7.util.get_bool(start_byte, 0, 5) # Read fifth bit from byte
# Write bool to byte, the byte is only local in python, 
# to apply change in PLC, you have to write the byte to PLC.
snap7.util.set_bool(start_byte, 0, 5, False) 
client.db_write(50, 0, start_byte)