需要安装
pip install python-snap7
import snap7
from snap7.util import *
import struct
# PLC的IP地址, Rack和Slot
plc = snap7.client.Client()
plc.connect('127.0.0.1', 0, 1) # IP, Rack, Slot
# 读取DB1中的10个字节,起始于0位置
db_number = 1
start = 0
size = 10
data = plc.db_read(db_number, start, size)
# 将数据按照每两个字节转换为int16
int16_values = []
for i in range(0, len(data), 2):
# 使用struct解包两个字节
value = struct.unpack('>h', data[i:i+2])[0]
int16_values.append(value)
print("读取的数据(int16):", int16_values)
# 断开连接
plc.disconnect()