Examples of Directly Reading and Writing PLC I/Q Areas and DB Blocks with Python

It is recommended to use the python-snap7 library, which provides comprehensive support for reading and writing the I/Q areas and DB blocks of Siemens S7 series PLCs. Below are two of the most commonly used examples:Reading and Writing I/Q Areas and Reading and Writing DB Blocks.1. Install

pip install python-snap7

2. Connect to the PLC

import snap7

# Create client

plc = snap7.client.Client()

# Connect to PLC (IP, rack, slot)

plc.connect(“192.168.0.1”, 0, 1)

print(“PLC Connected:”, plc.get_connected())

3. Read and Write I/Q Areas (Input/Output Image Area)

I Area = Inputs, Q Area = Outputs.

from snap7.util import get_bool, set_bool

# Read Q Area (Output Area), for example Q0.0

data = plc.read_area(snap7.types.Areas.PA, 0, 0, 1) # PA=Process Outputs

q0_0 = get_bool(data, 0, 0) # byte=0, bit=0

print(“Q0.0 =”, q0_0)

# Write Q0.0 = True

set_bool(data, 0, 0, True)

plc.write_area(snap7.types.Areas.PA, 0, 0, data)

4. Read and Write DB Blocks

Assuming there is an <span>INT</span> at offset 0 in DB1.

from snap7.util import get_int, set_int

# Read INT at offset 0 in DB1

data = plc.read_area(snap7.types.Areas.DB, 1, 0, 2) # DB1, offset 0, length 2 bytes

value = get_int(data, 0)

print(“DB1.DBB0 (INT) =”, value)

# Write new value 1234

set_int(data, 0, 1234)

plc.write_area(snap7.types.Areas.DB, 1, 0, data)

5. Explanation

  • Areas.PE → Input Area (I)

  • Areas.PA → Output Area (Q)

  • Areas.DB → Data Block (DB)

  • The offset and data type must match the definitions in the PLC program; otherwise, reading and writing errors will occur.

  • <span>python-s7comm</span> library is more low-level, with strong protocol parsing capabilities, but in practical engineering, snap7 is more stable.

If this article has been helpful to you, remember to like/bookmark it for future reference.

You are also welcome to share your experiences or opinions in the comments section to benefit more people.

If you find it valuable, share it with friends to learn and grow together. Have a great weekend!

Latest version of SINAMICS STARTER V5.7 installation and virtual machine download

Control mode and tail positioning calculation method for cold rolling and coiling machine (purely practical content)

Leave a Comment