Python-Snap7获取西门子PLC 300数值
说明
在一次数采项目中,对现场PLC300进行取数。本人小白,在网上搜罗了大量信息,终于找到解决方法。
准备事项
1. 操作系统
2.Python环境(本次使用Python3.6.6)
3.Snap7
connect
1 |
connect('192.168.0.1', rack=0,slot=1) |
三个参数分别为:IP 地址,机架,插槽
read_area及write_area
函数
1 2 3 |
read_area(self,area,dbnumber,start,size)#读取数值 write_area(self,area,dbnumber,start,data) #写入数值(未测试) |
参数area:
两个函数的核心都是对area进行读写操作,area用于区分I、Q、M、DB区域(西门子PLC中存储区有I、Q、M、DB、V区等等,本人为小白,此处不做具体了解),针对各个分区都有指定的值。具体如下:
1 2 3 4 5 6 |
'PE': 0x81, #input 输入区 'PA': 0x82, #output 输出区 'MK': 0x83, #bit memory 中间存储区(M区) 'DB': 0x84, #DB区 'CT': 0x1C, #counters 'TM': 0x1D, #Timers |
参数dbnumber:
dbnumber只有在对DB块使用时才有用,默认设置为0。
备注:
此次项目以取DB区域数值为主,未做其它区域测试,在PLC中,有很多的DB块,每个块中,分别存储不同的信息,个人理解此处更类似于电脑中的硬盘分区,每个DB块是一个分区,PLC将指定的数值存储在指定硬盘分区中。
参数start:
例如取DB7.10地址上的值
start起始地址为10,即PLC中的偏移地址。
参数size:
size是选择读取的数据类型占用地址位的尺寸,即占几个地址,如下:
示例
获取DB7.46的REAL值:
1 2 3 4 5 6 7 |
import snap7 from snap7.util import * from snap7.snap7types import * PLC_obj=snap7.client.Client() PLC_obj.connect('192.168.0.1',rack=0,slot=2) Real_Value=PLC_obj.read_area(0x84,7,46,4) get_real(Real_Value,0) |
断开连接:
1 |
PLC_obj.disconnect() |
备注
在获取S7WLByte数值时,需要使用get_int来获取数值,但是在获取数值时,会提示以下错误:
1 2 3 4 5 6 7 |
>>> Real_Value=PLC_obj.read_area(0x84,7,0,1) >>> get_int(Real_Value,0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/software/Python3.6.6/lib/python3.6/site-packages/snap7/util.py", line 149, in get_int data[1] = data[1] & 0xff IndexError: bytearray index out of range |
解决方法:
提高get_area的尺寸长度,但是获取到的数值和实际数值不符,需要在获取到的数值的基础上除以256,才是实际的数值。
1 2 3 |
>>> Real_Value=PLC_obj.read_area(0x84,7,0,25) >>> get_int(Real_Value,0) 3859 |
参考资料
python snap7读写西门子s7-1200PLC的数据(PLC的I、Q、M、DB、V区)
采用snap7实现对PLC1200的I、Q、M、DB区域进行读写
二〇二〇年四月十四日 10:27:09
版权声明:
作者:龙魂
链接:https://blog.wlzs.cn/python-snap7%e8%8e%b7%e5%8f%96%e8%a5%bf%e9%97%a8%e5%ad%90plc-300%e6%95%b0%e5%80%bc/
文章版权归作者所有,未经允许请勿转载。
THE END