Search code examples
javascriptnode-red

Adding the first 5 values to compute offset


I am using node-red to get the signal of my load cell. I receive the value of the load cell using MQTT (from my python script), then I would like to save the first 5 value coming from MQTT to compute the offset of my load cell. Then when I will have my offset, I can subtract it from my msg.payload to set the load cell to 0.

I have tried to make a while loop to accumulate the first 5 value but the result is updating even if the first 5 values are gone. It looks like it applied the computation that is inside my loop even if the loop is over.

var offset0 = 0;
var i = 0;


while (i < 5) {
    offset0 = parseFloat(msg.payload) + offset0;
    i = i + 1;
}
offset0 = offset0 / 5;


msg.payload = offset0;
return msg;

msg is updating after each new coming from my load cell... or I'd like to keep only the first 5 values (5 is for making a test, then I'd like to use more than 5 points).

For example, here is the data I get from my load cell :

1.93, 1.94, 1.95, 1.94, 1.96, 1.93, 1.88, 1.93. 

It should take the first 5 :

1.93, 1.94, 1.95, 1.94, 1.96 

And make the mean.


Solution

  • There are a number of problems with your approach.

    First,by default the function node (where your code is running) doesn't keep any state. This means that offset0 will be reset to 0 for every incoming message.

    Second, the code is triggered by an incoming message, this means that while() loop will always run with the same value (what ever was in msg.payload for the message that triggered the node)

    You need to make use of what is known as the context to store values between messages arriving at the function node.

    Something a like this should be a starting point:

    //get current offset array from context or empty array
    var offset = context.get('offset') || [];
    
    //if less than 5 readings store value and do not send on message
    if (offset.length < 5) {
      offset.push(msg.payload);
      context.set('offset',offset);
      return;
    } else {
      //otherwise calculate mean and remove from value and forward.
      var o;
      for (var i=0; i<5; i++) {
        o += offset[i];
      }
      msg.payload = msg.payload - (o/5);
      return msg;
    }