What is Python snap7? How to connect Siemens PLC with Python snap7?

30 January 2023 4835 Reading time: 2 minute

Python-snap7 is a Python wrapper for the snap7 library, which is a communication library for interfacing with Siemens S7 PLCs (Programmable Logic Controllers). It allows you to read and write data to/from the PLC and communicate with it over a network using the Siemens S7 communication protocol. The library provides functions for data exchange between a Python application and the PLC, making it possible to integrate the PLC into automation systems.

Here's an example of how to establish a connection to a Siemens S7 PLC using the python-snap7 library:


import snap7

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

if plc.get_connected():
    print("Successfully connected to PLC.")
else:
    print("Connection to PLC failed.")

plc.disconnect()

In this example, the Client object from the snap7 library is created, and the connect method is used to establish a connection to the PLC at IP address 192.168.1.1 on rack 0, slot 1. The get_connected method is used to check the connection status, and if the connection is successful, the Successfully connected to PLC message is printed. Finally, the disconnect method is used to close the connection. Note that this is just a basic example and you will need to provide more specific information (e.g. IP address, rack, and slot of the PLC) and additional code to read/write data from/to the PLC. The python-snap7 library provides many functions for accessing different types of data (e.g. bit, byte, word, integer, float, etc.) and for different data structures (e.g. DB, input, output).

Reading and writing data with python-snap7

I present an example for reading and writing data from a Siemens S7 PLC using the python-snap7 library:


import snap7

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

if plc.get_connected():
    # Read a Boolean value from the PLC's input area
    input_byte = plc.read_area(snap7.types.areas.MK, 0, 0, 1)
    input_bool = snap7.util.get_bool(input_byte, 0, 0)
    print("Read input value:", input_bool)

    # Write a Boolean value to the PLC's output area
    output_byte = snap7.util.build_byte(output_bool, 0)
    plc.write_area(snap7.types.areas.PK, 0, 0, output_byte)
    print("Wrote output value:", output_bool)

else:
    print("Connection to PLC failed.")

plc.disconnect()

In this example, a Boolean value is read from the PLC's input area using the read_area method and checked if it is read correctly using the get_bool function. Then, a Boolean value is written to the PLC's output area using the write_area method. Note: The MK and PK values are given as an example and these values must match the addresses in your PLC. Similarly, the 0, 0, and 1 values are given as an example and these values must match the data in your PLC.

Similar articles