Need to change 0's to 1 and 1's to 0

Hi, I'm a bit new to this and i'm having some issues in changing/replacing/inverting the messages from 0 to 1 / from 1 to 0. Its from some optocouplers that send a 0 when they are on and a 1 when they are off. I've tried using a change node and always seem to get 0's.

And the same zeros when using a function node.

Hello @Goldog welcome to the forum.

You need three operations in your change node:

  • change 1 to "anything"
  • change 0 to 1
  • change "anything" to 0

@Goldog That output is expected if you follow the logic you have given :slight_smile:

1st - you change any 0 to 1, so a 0 payload is now 1 and a 1 payload is still 1
2nd - you then change any 1 to 0, since any payload you sent is now 1 it will always change to zero.

You can do this in a function node

msg.payload = msg.payload === 1 ? 0 : 1;
return msg;

This checks if the payload is 1, if it is it returns 0, if not it returns 1

Hello @jbudd, Thanks so much i knew it had to be simple

@smcgann99 thanks for the logic explanation, makes perfect sense. i do get caught out by thinking in sequential terms and forgetting about the alternatives still flowing through.

For completeness, to explain the reason your function did not work, where you have
if (msg.payload = 1) {
the bit in the parenthesis, = is an assignment operator which says 'set message.payload to the value 1'. What you want is the comparison operator === which compares msg.payload to the value 1 and returns true or false. You could also use ==. The difference is subtle and I will leave it for you to research the difference.

Just to point out that even if you had used the correct ===, the function would still fail.
So if payload equals 1

if(msg.payload === 1){
    msg.payload = 0 // payload now equal to 0
if(msg.payload === 0){
    msg.payload = 1 // payload was set to zero this now resets it to 1

You should use else or else if

if(msg.payload === 1){
    msg.payload = 0 // payload now equal to 0
}else if(msg.payload === 0){ // this section does not execute as first if is true.
    msg.payload = 1 


if(msg.payload === 1){
    msg.payload = 0 // payload now equal to 0
}else {
    msg.payload = 1 // this section only executes if payload does not equal 1

If boolean as answer is no problem

msg.payload = !msg.payload
1 Like