樹莓派上的40個GPIO是最好玩的東西html
它們能夠被C,/C++, Python, Java等語言直接控制node
如今就來看看怎麼用Node.js作到一樣的事情json
在試驗以前, 請先安裝好Node.js, 具體能夠移步到: <樹莓派.安裝系統+Node.js+MongoDB系列環境>oop
1.準備試驗文件夾post
mkdir /home/pi/Documents/test-gpio-demo/
2.建立文件package.jsonui
{ "name": "test-gpio-demo", "version": "0.0.1", "dependencies":{ "rpio2":"0.4.1" } }
3.建立主文件blank.jsspa
//blink.js const Gpio = require('/home/pi/Documents/test-gpio/node_modules/rpio2/lib/index.js').Gpio; var led = new Gpio(36); //建立 P36 引腳 led.open(Gpio.OUTPUT, Gpio.LOW); //設置爲 OUTPUT、默認低電平 for(var i = 0; i < 20; i++){ led.toggle(); //切換 led 的電平狀態 led.sleep(300); //等待 500ms } led.close();
4.硬件電路鏈接code
第36腳(GPIO16) 通過一個電阻(220歐或1K均可以),再接到LED的正級htm
LED負級接到第34腳(GND)blog
5.試運行
node /home/pi/Documents/test-gpio-demo/blank.js
閃燈效果:
亮燈
滅燈:
試驗成功!
===============================分隔線=========================
rpio2常規用法:
Synchronously
const Gpio = require('./lib/index.js').Gpio; const gpio = new Gpio(40); gpio.open(Gpio.OUTPUT); for(var i = 0; i < 10; i++){ gpio.toggle(); gpio.sleep(500); } gpio.close();
Asynchronously
const Gpio = require('../lib/index.js').Gpio; const gpio = new Gpio(40); gpio.open(Gpio.OUTPUT); void function loop(){ Promise.resolve(gpio.toggle()) .then(gpio.sleep.bind(null, 500, true)) .then(loop) }(); process.on("SIGINT", function(){ gpio.close(); console.log('shutdown!'); process.exit(0); });
Toggle with button
const Gpio = require('../lib/index.js').Gpio; const button = new Gpio(32); const output = new Gpio(40); button.open(Gpio.INPUT); output.open(Gpio.OUTPUT, Gpio.LOW); //button down button.on('rising', function(){ output.toggle(); }); process.on("SIGINT", function(){ button.close(); output.close(); console.log('shutdown!'); process.exit(0); });