使用 node.js 和 onoff 提高 LED 在 Raspberry Pi 上的闪烁速度

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

我正在尝试使用变量 'counter' 来改变间隔。

Twitter 流正在运行,LED 正在闪烁。

我已删除所有 Twitter 凭据。

如有任何帮助,我们将不胜感激!

这是我的代码:

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;

            }

});

一旦您拨打了 setInterval() 电话,计时器就会锁定,您无法更改它。这就是函数参数的工作方式:事后更改它们什么都不做。提供的值没有绑定,数字作为副本传入。

您需要清除并重新设置计时器。 setInterval() returns 可以传递给 clearInterval() 的句柄以将其关闭。你已经捕获了这个,所以你只需要使用它:

var iv;

function blink(interval) {
  if (iv) {
    clearInterval(iv);
  }

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

然后使用这个函数重置它:

counter -= 100;
blink(counter);

只要确保你不会消极。

我添加了一个检查计数器和间隔:

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 = 200;

stream.start();

var iv;

function blink(interval) {
  if (iv) {
    clearInterval(iv);
  }
if (interval <= 100) {

interval = 100;

}
console.log("interval = " + interval);

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

}

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

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


                counter += 100;
                    if (counter <= 100) {
                counter = 100;
}
                console.log(counter);
                blink(counter);

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

                console.log("peace");
                counter -= 100;
                if (counter <= 100) {
                counter = 100;
                }
                console.log(counter);
                blink(counter);

            }

});