How can I take average of modbus datas?

Hi everyone ,

I'm new in Node-Red. I'm trying to get data from Modbus Tcp(Modbus Read Node) and take average of these datas value .However these datas array be restricted by digital data which is come from S7 PLC.When digital data is 1 I should start to get data , when digital data is 0 I should stop getting data and take average of them . This situtation should continue like this .I have no problem in connection between modbus or S7 and node-red . How can I do that ?

If any body help , I will be really appreciate.

most probably you need to use Context to store whether the digital data is 1 or 0 and make decisions and calculations based on that.
the analog data is also stored in Context in an array until a digital 0, where you calculate the average.

Here's an example flow that can modify according to your needs :

[{"id":"9db9ad529c0f5deb","type":"inject","z":"4895ea10b4ee9ead","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"1","payloadType":"num","x":350,"y":880,"wires":[["e9314f4a667a9427"]]},{"id":"46e0cb98389a311f","type":"inject","z":"4895ea10b4ee9ead","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"0","payloadType":"num","x":350,"y":960,"wires":[["e9314f4a667a9427"]]},{"id":"65b684fb4c082448","type":"inject","z":"4895ea10b4ee9ead","name":"analogValue","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"analogValue","payload":"$random() * 10","payloadType":"jsonata","x":330,"y":1040,"wires":[["d9a97784efe64426"]]},{"id":"d9a97784efe64426","type":"function","z":"4895ea10b4ee9ead","name":"calculate average","func":"let digitalValue = flow.get('digitalValue')\nlet analogValue = flow.get('analogValue') || []\n\n\nif (digitalValue === 1) {\n    analogValue.push(msg.payload)\n    flow.set('analogValue', analogValue)\n    return null\n}\n\n\nif (digitalValue === 0 && analogValue.length > 1) {\n    let sum = analogValue.reduce((a, b) => a + b, 0)\n    let avg = sum / analogValue.length\n    msg.payload = avg;\n    flow.set('analogValue', [])\n    return msg\n}\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":550,"y":1040,"wires":[["de1875c86df3ba34"]]},{"id":"de1875c86df3ba34","type":"debug","z":"4895ea10b4ee9ead","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":790,"y":1040,"wires":[]},{"id":"e9314f4a667a9427","type":"function","z":"4895ea10b4ee9ead","name":"set digitalValue Context","func":"flow.set(\"digitalValue\", msg.payload)\nreturn null;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":570,"y":920,"wires":[[]]}]

ps. alternatively you could install and try out the Smooth node that does some averaging
node-red-node-smooth