使用python-snap7与PLC西门子1500 CPU连接

问题描述 投票:0回答:1

您好,我尝试使用 Python 连接 PLC 西门子 CPU 1500,并使用 snap7 库。我可以成功地将自己与CPU连接起来。但是当我尝试读取和写入在 OB1 和 DB1 中初始化的数据时,出现以下错误:

    readbit = ReadMemory(plc, 0, 0, S7WLBit) #read m0.0

  File c:\users\rachid\.spyder-py3\sps.py:22 in ReadMemory
    result = plc.read_area(areas['MK'],0,byte,datatype)

  File ~\anaconda3\Lib\site-packages\snap7\client\__init__.py:390 in read_area
    if area not in Areas:

  File ~\anaconda3\Lib\enum.py:740 in __contains__
    raise TypeError(

TypeError: unsupported operand type(s) for 'in': 'int' and 'EnumType'

这是我的代码:

import snap7
from snap7.util import*
from snap7.types import*
import time


def ReadMemory(plc,byte,bit,datatype):
    result = plc.read_area(areas['MK'],0,byte,datatype)
    if datatype==S7WLBit:
        return get_bool(result,0,1)
    elif datatype==S7WLByte or datatype==S7WLWord:
        return get_int(result,0)
    elif datatype==S7WLReal:
        return get_real(result,0)
    elif datatype==S7WLDWord:
        return get_dword(result,0)
    else:
        return None
    
    
def WriteMemory(plc,byte,bit,datatype,value):
    result = plc.read_area(areas['MK'],0,byte,datatype)
    if datatype==S7WLBit:
        set_bool(result,0,bit,value)
    elif datatype==S7WLByte or datatype==S7WLWord:
        set_int(result,0,value)
    elif datatype==S7WLReal:
        set_real(result,0,value)
    elif datatype==S7WLDWord:
        set_dword(result,0,value)
    plc.write_area(areas['MK'],0,byte,result)       


# Verbindung zur SPS herstellen
plc = snap7.client.Client()
plc.connect(spshost, 0, 1)     #IP, RACK , SLOT 

state = plc.get_cpu_state()
print(f'State:{state}')

a = 0
b = 0
c = 0
while True:
    readbit = ReadMemory(plc, 0, 0, S7WLBit) #read m0.0
    print('readbit: ', readbit)
    readword = ReadMemory(plc, 10, 0, S7WLWord) #read mw10
    print('readbyte: ',readword)
    readreal = ReadMemory(plc, 15, 0, S7WLReal) #read md15
    print('readreal: ',readreal)
    readDword = ReadMemory(plc, 20, 0, S7WLDWord) #read md20
    print('readDword: ', readDword)
    
    a = a+1
    b = b+2.4
    c = c+10
    #write memory
    WriteMemory(plc, 0, 3, S7WLBit, True) #write m0.3 True
    time.sleep(1)
    WriteMemory(plc, 0, 3, S7WLBit, False) #write m0.3 False
    time.sleep(1)
    WriteMemory(plc, 30, 0, S7WLWord, a) #write mw30 valuefrom a variable
    WriteMemory(plc, 40, 0, S7WLReal, b) #write md40 value
    WriteMemory(plc, 50, 0, S7WLDWord, c) #write md50 value

我和这个人做同样的事情:https://www.youtube.com/watch?v=u1WQFP2l29k

您能帮助我并告诉我如何修复该错误吗?

谢谢!

python plc siemens tia-portal snap7
1个回答
0
投票

更改区域。['MK'] 为区域.MK

© www.soinside.com 2019 - 2024. All rights reserved.