100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > 树莓派与node.js —— onoff dht

树莓派与node.js —— onoff dht

时间:2020-03-10 23:36:45

相关推荐

树莓派与node.js —— onoff dht

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 () {//#Cvar value = (led.readSync() + 1) % 2; //#Dled.write(value, function () {//#Econsole.log("Changed LED state to: " + value);});}, 2000);process.on('SIGINT', function () {//#FclearInterval(interval);led.writeSync(0); //#Gled.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();});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。