樹莓派.使用Node.js控制GPIO

來源:互聯網
上載者:User

標籤:ons   span   idt   lib   log   image   style   python   硬體   

樹莓派上的40個GPIO是最好玩的東西

它們可以被C,/C++, Python, Java等語言直接控制

現在就來看看怎麼用Node.js做到同樣的事情

在實驗之前, 請先安裝好Node.js, 具體可以移步到: <樹莓派.安裝系統+Node.js+MongoDB系列環境>

 

1.準備實驗檔案夾

mkdir /home/pi/Documents/test-gpio-demo/

 

2.建立檔案package.json

{  "name": "test-gpio-demo",  "version": "0.0.1",  "dependencies":{    "rpio2":"0.4.1"  }}

3.建立主檔案blank.js

//blink.jsconst 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.硬體電路串連

第36腳(GPIO16) 經過一個電阻(220歐或1K都可以),再接到LED的正級

LED負級接到第34腳(GND)

 

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 downbutton.on(‘rising‘, function(){  output.toggle();});process.on("SIGINT", function(){  button.close();  output.close();  console.log(‘shutdown!‘);  process.exit(0);});

 

樹莓派.使用Node.js控制GPIO

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.