Reputation: 69
Hello I try to connect with a PLC Siemens CPU 1500 with Python and i use the snap7 library. I can sucessfull connect myself with the CPU. But when I try to read and write data which I initialized in the OB1 and DB1 I got the following error:
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'
Here is my code:
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
I do the same as this guy: https://www.youtube.com/watch?v=u1WQFP2l29k
Can you please help me and tell me how to fix the error?
Thank you!
Upvotes: 0
Views: 633