XY BLOG

XY的BLOG

python连接西门子PLC

Published on in Posts
Updated on
Short link: https://b.xyzt07.cn/s/1
Share this post
A ⇄ 文
⚠️ This entry is already over one year old. It may no longer be up to date. Opinions may have changed.

snap7连接200 smart

连接

from snap7 import util, client, types

plc_ip = "192.168.7.100"
rack = 0
slot = 1

my_plc.set_connection_type(1)  # 如果连接的是s7-200smart系列plc
# set_connection_params(ip, local_tsap, remote_tsap)  如果连接的是logo!系列plc
my_plc.connect(plc_ip, rack, slot)
print(my_plc.get_connected())

读取

#V、I、Q、M、S、L 和 SM
'''
PE = 0x81 #I区
PA = 0x82 #Q区
MK = 0x83 #M区
DB = 0x84 #V区
CT = 0x1C #Counter
TM = 0x1D #Timer
'''


#db_number: number of the DB to be read. V区数据块
#start: byte index from where is start to read from.
#size: amount of bytes to be read.
dbnumber = 1
start = 0
size = 8

m0_buffer = my_plc.read_area(types.Areas.PE, dbnumber, start, size)#读取区域

#开关量bool值读取
byte_index = 0
bit_index = 1
util.get_bool(m0_buffer, byte_index, bit_index)#读取M0.1地址
util.get_bool(m0_buffer, 0, 0)#读取M0.0地址
util.get_bool(m0_buffer, 0, 3)#读取M0.3地址

m1_buffer = my_plc.read_area(types.Areas.PE, dbnumber, 1, size)#读取区域
util.get_bool(m1_buffer, 0, 3)#读取M1.3地址


#start 0-8191 
byte_arrays = my_plc.db_read(dbnumber, start, size)#此方法读取为V区数据

#start 0-31 size 1-31

byte_arrays = my_plc.mb_read(start, size)#读取M区数据


写入

dbnumber = 1
start = 0
size = 8


byte_index = 0
bit_index = 1

m0_buffer = my_plc.read_area(types.Areas.PE, dbnumber, start, size)#读取区域

util.get_bool(m0_buffer, byte_index, bit_index)#读取M0.1地址

util.set_bool(m0_buffer, byte_index, bit_index,True)#设置值为True

my_plc.mb_write(start, size, m0_buffer)#写入PLC




my_plc.db_write(dbnumber, start, buffer)#写入V区数据

my_plc.mb_write(start,size,buffer)#写入M区数据


官方文档