Sjoenne
Posts: 2
Joined: Tue Apr 18, 2017 8:03 pm

Node Red toggle function

Mon Jun 19, 2017 7:50 pm

Hi!

Been fooling around with node-red for a simple application to make a pushbutton that sends tcp commands to third party gear.

I've run into a problem with the GPI. I want to send different commands on every second pulse from a momentary switch on the GPI. Its normally 1 and changes to 0 on button press. Is there a way to insert a function to send 1 on the first pulse, 0 on the next, 1 on the third and so on?

Hope you can help me :)


zoppolig
Posts: 2
Joined: Fri Jan 12, 2018 6:16 pm

Re: Node Red toggle function

Fri Jan 12, 2018 6:23 pm

I did it with this messy function I made up from various input from the link provided by DirkS and the idea of counting whether the button push/pull doublet I'm doing is even or odd. I suspect there must be an easier way...

Paste this into a function between the rp.gpio input (the button) and the rp.gpio output (the LED):

context.state = context.state | false;
context.state = !context.state
var myContext = context.state;
// initialise the counter to 0 if it doesn't exist already
var count = context.get('count')||0;
count += 1;
// store the value back
context.set('count',count);
// make it part of the outgoing msg object
msg.count = count;
//define function isOdd 1 === isOdd
function isOdd(num) { return num % 2;}
/*if myContext is true and count is odd send 1,
else send 0 */
if(myContext === true && isOdd((count+1)/2) ===1){
msg.payload = 1;
return msg;
} else if (myContext === true && isOdd((count+1)/2) ===0){
msg.payload = 0;
return msg;
}

zoppolig
Posts: 2
Joined: Fri Jan 12, 2018 6:16 pm

Re: Node Red toggle function

Fri Jan 12, 2018 6:29 pm

PS actually, I realized the first part of my function is pretty useless, here is the simplified version. Basically set a global context counter and if it's odd, you switch on, else you switch off:

// initialise the counter to 0 if it doesn't exist already
var count = context.get('count')||0;
count += 1;
// store the value back
context.set('count',count);
// make it part of the outgoing msg object
msg.count = count;
//define function isOdd 1 === isOdd
function isOdd(num) { return num % 2;}
/*if count is odd send 1,
else send 0 */
if(isOdd((count+1)/2) ===1){
msg.payload = 1;
return msg;
} else if (isOdd((count+1)/2) ===0){
msg.payload = 0;
return msg;
}

Return to “Other languages”

Who is online

Users browsing this forum: No registered users and 2 guests