Modbus negative numbers

I need some help please to get Modbus numbers reading correctly when they go negative.

When the output from my modbus device goes negative it adds 65535 to the number.

I have tried various settings in a few different Modbus input nodes, but they all give the same output.
I have also tried a few of the function nodes but none seem to solve the problem.

I thought it may be quite simple to write a "function" node, but I have no idea with java script.

What I want is:

if msg.payload > 2000;
then msg.payload = msg.payload - 65535;
else return msg.payload;
endif;

Those of you who understand thees things will know I am getting all sorts of error messages on each line. I suspect it just needs some minor grammar and layout adjustments but I have not found any java script grammar tutorials that show what I need to do?

Thank you

Hi @RickW - you're missing a few brackets and braces:

if (msg.payload > 2000) {
  msg.payload = msg.payload - 65535;
}
return msg;

Here's a good guide on the basics of conditional statements in JavaScript - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/conditionals

The other pages around that one cover other useful topics.

Thank you knolleary!

I thought I wasn't too far off.

My mistake... The last line should be return msg ... I have edited my previous reply to fix it.

I think it might be better to use 32767 which is the maximum 16 bit signed integer. Also I think it should be 65536 that you take off, not 65535. The hex value 0xFFFF is 65535 which should convert to -1.

Thank you.

I did get an error and was trying a few things.
Is working now.

Much appreciated!

I agree with your updated numbers.

My particular application will never have valid readings above 2000, but using 32767 would be better in case other applications have higher valid numbers.

I bow to your argument for for the subtract number. Either number appears to function in a smooth linear trend. My current application doesn't have a direct reference I can compare it against.

Thanks again.