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.
@Goldog That output is expected if you follow the logic you have given
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.
@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
}
or
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
}