1. 发光二极管

tm-onoff

var Gpio = require('tm-onoff').Gpio,
led = new Gpio(17, 'out'),
button = new Gpio(18, 'in', 'both');
// 'both':按钮的上升下降沿都应该被处理,即调用如下的函数
button.watch(function(err, value) {
led.writeSync(value);
});

上述代码在ctrl+c退出时,并未释放资源,也未处理错误,一份更完整的处理如下:

var Gpio = require('tm-onoff').Gpio,
led = new Gpio(17, 'out'),
button = new Gpio(18, 'in', 'both'); button.watch(function(err, value) {
if (err) exit();
led.writeSync(value);
}); function exit() {
led.unexport();
button.unexport();
process.exit();
} process.on('SIGINT', exit);
  • 通过调用 led、btn 的 unexport 方法以释放其资源;

    var onoff = require('onoff');
    var Gpio = onoff.Gpio,
    led = new Gpio(4, 'out'),
    interval; interval = setInterval(function () { //#C
    var value = (led.readSync() + 1) % 2; //#D
    led.write(value, function () { //#E
    console.log("Changed LED state to: " + value);
    });
    }, 2000); process.on('SIGINT', function () { //#F
    clearInterval(interval);
    led.writeSync(0); //#G
    led.unexport();
    console.log('Bye, bye!');
    process.exit();
    });

2. dht:温湿度传感器

GitHub - momenso/node-dht-sensor: Node.js Humidity and Temperature sensor addon

  • node-dht-sensor 的安装使用如下命令:

    $ npm install --save node-dht-sensor
    
    # 如果存在权限问题,使用
    
    $ sudo npm install --unsafe-perm --save node-dht-sensor
var dhtLib = require('node-dht-sensor');
dhtLib.initialize(11, 12);
// 第一个参数表示传感器类型,dht11使用11,dht22使用22
// 第二个参数表示GPIO引脚号
var interval = setInterval(function (){
read();
}, 2000);
function read() {
var readout = dhtLib.read();
console.log('Temperature: ' + readout.temperature.toFixed(2) + 'C, ' +
'humidity: ' + readout.humidity.toFixed(2) + '%');
};
process.on('SIGINT', function () {
clearInterval(interval);
console.log('Bye, bye!');
process.exit();
});
05-04 11:01