0

Im a beginner in PLC programming and python. My requirement is to read the Global Data Block using python programming. I have used the following code snippet.

Code:

import snap7 #import library snap7
from snap7.util import*
from snap7.types import*
import time #import library time
def ReadMemory(plc,byte,bit,datatype): #define read memory function
    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
        

IP = '192.168.x.xx' #IP plc
RACK = 0 #RACK PLC
SLOT = 1 #SLOT PLC

plc = snap7.client.Client() #call snap7 client function
plc.connect(IP,RACK,SLOT) #connect to plc

state = plc.get_cpu_state() #read plc state run/stop/error
print(f'State:{state}') #print state plc
# a = 0
# b = 0
# c = 0
while True:
#read memory
    readbit = ReadMemory(plc,0,0,S7WLBit) 

PLC Data Block Details:Data Block

Address associated with TagsAddress Tags

Program Errors:

Traceback (most recent call last):
  File "C:\Users\Dinesh-AMS\PycharmProjects\Python Plc Siemens\snap7com\python_program\venv\Python.py", line 45, in <module>
    readbit = ReadMemory(plc,0,0,S7WLBit) #read m0.0
  File "C:\Users\Dinesh-AMS\PycharmProjects\Python Plc Siemens\snap7com\python_program\venv\Python.py", line 6, in ReadMemory
    result = plc.read_area(areas['PE'],0,byte,datatype)
  File "C:\python\lib\site-packages\snap7\client.py", line 392, in read_area
    if area not in Areas:
  File "C:\python\lib\enum.py", line 373, in __contains__
    raise TypeError(
TypeError: unsupported operand type(s) for 'in': 'int' and 'EnumMeta'
State:S7CpuStatusRun

Could anyone tell me why my program throwing this error and help me to resolve this issue?

DRV
  • 676
  • 1
  • 8
  • 22
  • The error sounds like `areas['PE']` is an `int` instead of the expected `snap7.types.Areas`. Have you printed out its value and type to make sure you're passing the right data? – Jan Wilamowski Dec 28 '21 at 08:38
  • I am not sure which values to pass – DRV Dec 28 '21 at 12:11
  • I have tried all values in the areas such as 'PE','PA','DB','MK' etc but the program is failed to compile. @JanWilamowski – DRV Dec 29 '21 at 07:12
  • have you printed out their values and types? e.g. `print(areas['MK'], type(areas['MK'])` – Jan Wilamowski Dec 30 '21 at 03:39

1 Answers1

0

You have to change result = plc.read_area(areas['MK'],0,byte,datatype) to result = plc.read_area(snap7.types.Areas.MK,0,byte,datatype)