Add two numbers

#1

Hello.

I find myself in a situation that I can’t resolve.

I need to add two numbers, msg.pid and msg.temperature, I have tried a function in all the ways I know and never get the result.

Could someone please provide me with the necessary code?

Thank you very much.

1 Like

#2

Hi @underpop

can you share some of what you’ve tried? It’s hard to say where you may be going wrong if you don’t show us anything.

If those two properties are numbers, not strings, then you can do:

msg.payload = msg.pid + msg.temperature;
return msg;

This code assumes you want the result of the sum placed in the payload of the message the Function sends on.

0 Likes

#3

Does this thread help ? Deduct old payload from new payload

0 Likes

#4

It doesn't work.

The result is NaN.

Here's a snapshot of the flow:

0 Likes

#5

@underpop okay - so it looks like msg.pid and msg.temperature are actually different messages - they are not two properties on the same message object.

The Function node is run each time a message arrives. So it will be run when the msg with pid arrives, and it will be run again when the msg with temperature arrives. But at no time does the Function have both messages.

To make this work you need to store the value of msg.pid and msg.temperature in Flow Context - so their values can be retrieved whenever a message arrives.

For example:

// store pid/temperature in flow context
if (msg.hasOwnProperty("pid")) {
    flow.set('pid', msg.pid);
} else if (msg.hasOwnProperty("temperature")) {
   flow.set('temperature', msg.temperature);
}


// get the latest values of pid/temperature from context - default to 0 if not yet set
var pid = flow.get('pid') || 0;
var temperature = flow.get('temperature') || 0;
msg.payload = pid+temperature;
return msg

More on flow context in the docs: https://nodered.org/docs/writing-functions

1 Like

#6

I’t works.

Now i understand my error.

Thank you very much!

0 Likes

#7

By the way, if you are doing PID control you might like to look at https://flows.nodered.org/node/node-red-contrib-pid

0 Likes