Apply IIR Low-pass Filter to MQTT value

Take incoming value from MQTT topic get/ESP8266/counterValue and apply and IIR (Infinate Impulse Response) Low-pass filter to it and output to topic get/ESP8266/filterValue. The filter constant can be set via topic set/ESP8266/filterConstant. Most functionality resides in the main filter function.

[{"id":"80804206.7f7fc","type":"mqtt-broker","broker":"localhost","port":"1883","clientid":""},{"id":"22f2ce73.dd0d32","type":"mqtt in","name":"","topic":"get/ESP8266/counterValue","broker":"80804206.7f7fc","x":146,"y":90,"z":"1e47102.fe1b8f","wires":[["4b72bd0e.b48d44"]]},{"id":"4b72bd0e.b48d44","type":"function","name":"Filter","func":"switch (msg.topic) {\n  case \"get/ESP8266/counterValue\":\n    context.filterValue = context.filterValue || 0;\n    var filterConstant = context.filterConstant || 0.4;\n    var unfiltered = msg.payload;\n    var filtered = ((unfiltered - context.filterValue) * filterConstant) + context.filterValue;\n    context.filterValue = Math.round(filtered);\n    msg.topic = \"get/ESP8266/filterValue\";\n    msg.payload = context.filterValue;\n    return msg;\n    break;\n  case \"set/ESP8266/filterConstant\":\n    if (msg.payload >= 0.0 && msg.payload <= 1.0) {\n      context.filterConstant = msg.payload;\n      msg.topic = \"get/ESP8266/filterConstant\";\n      msg.payload = context.filterConstant;\n      msg.retain = true;\n      return msg;\n    }\n    break;\n}\n\nreturn null;","outputs":1,"x":456,"y":204,"z":"1e47102.fe1b8f","wires":[["a099df33.5f662","ec7fa690.138058"]]},{"id":"a099df33.5f662","type":"mqtt out","name":"MQTT out","topic":"","broker":"80804206.7f7fc","x":796,"y":262,"z":"1e47102.fe1b8f","wires":[]},{"id":"ec7fa690.138058","type":"debug","name":"","active":false,"console":false,"complete":false,"x":795,"y":123,"z":"1e47102.fe1b8f","wires":[]},{"id":"84c0cef8.7b3f3","type":"mqtt in","name":"","topic":"set/ESP8266/filterConstant","broker":"80804206.7f7fc","x":151,"y":248,"z":"1e47102.fe1b8f","wires":[["4b72bd0e.b48d44"]]}]
pprimm

Flow Info

created 2 years, 1 month ago

Node Types

Core
  • debug (x1)
  • function (x1)
  • mqtt in (x2)
  • mqtt out (x1)
  • mqtt-broker (x1)

Tags

  • filter
  • IIR
  • low-pass
Copy this flow JSON to your clipboard and then import into Node-RED using the Import From > Clipboard (Ctrl-I) menu option