Search code examples
pythoncycletwincattwincat-ads

Pyads read value on notification: when TwinCat cycle occured


I would like to read some values out of an SPS written in TwinCat 3 over ADS route with pyads. The values must be read when the cycle occured. In my Python script I get the cycle time of my SPS first. I defined a time to read (5000 ms), with the reading time and the detected cylce time (10 ms) I calculate the number of values to be read.

In a while loop i want to read the defined number of values.

In the code it looks something like this:

plc = pyads.Connection('172.18.51.64.1.1', 851)
plc.open()
cycle_time = plc.read_by_name('Main.lrCycleTime', pyads.PLCTYPE_LREAL)
time_to_read = 5000  #milliseconds
values_to_read = int(time_to_read/cycle_time)
count = 0
read_values = []
while count < values_to_read:
    count += 1
    array_PLC = plc.read_by_name('Main.arrNumbers', pyads.PLCTYPE_ARR_LREAL(2))
    read_values.append(array_PLC)

When I do this, I simply just poll some Values. That means every value exists multiple times and i do not read the predefined 5000 ms.

Is anybody familiar with the pyads-library? Are there any possibilities to get a kind of a notification when a cycle occured? I do not want to set a timer in the python script. Just to be sure not to skip a cycle while I read.


Solution

  • TwinCat Ads provides functionality to receive notifications. You can add/configure a notification to receive the value of a variable at different points(each cycle, on change...).

    pyads just wraps the TwinCatAds.Dll and provides a more comfortable Python interface as the documentation says.

    See this sample for notification