Search code examples
node.jstwitterraspberry-pigpioled

increase speed of LED blink on Raspberry Pi using node.js and onoff


I'm trying to alter the interval by using a the variable 'counter'.

The Twitter stream is working and the LED is blinking.

I have removed all the twitter credentials.

Any help would be greatly appreciated!

Here is my code:

var Gpio = require('onoff').Gpio;
var Twit = require('twit');
var T = new Twit({
    consumer_key:         '' // Your Consumer Key
  , consumer_secret:      '' // Your Co$
  , access_token:         '' // Your Ac$
  , access_token_secret:  '' // Your Access $
});

var stream = T.stream('statuses/filter', { track: '#blessed, #peace'})

led = new Gpio(17, 'out'),
counter = 500;

stream.start();

var iv = setInterval(function(){
        led.writeSync(led.readSync() === 0 ? 1 : 0);
}, counter);


stream.on('tweet', function(tweet) {

        if(tweet.text.indexOf('#blessed') > -1) {
                console.log("blessed");

                counter += 100;

            }  else if (tweet.text.indexOf('#peace') > -1) {

                console.log("peace");
                counter -= 100;

            }

});

Solution

  • Once you've made the setInterval() call, the timer's locked in, you can't change it. This is how arguments to functions work: Changing them after the fact does nothing. There is no binding to the value supplied, numbers get passed in as a copy.

    You'll need to clear and re-set the timer. setInterval() returns a handle you can pass through to clearInterval() to turn it off. You've captured this, so you just need to use it:

    var iv;
    
    function blink(interval) {
      if (iv) {
        clearInterval(iv);
      }
    
      iv = setInterval(function() {
        led.writeSync(led.readSync() === 0 ? 1 : 0);
      }, interval);
    }
    

    Then use this function to reset it:

    counter -= 100;
    blink(counter);
    

    Just make sure you don't go negative.