node.jsでGPIOとコンソールコマンドが使えるようになったので、起動するとLEDの点滅、スイッチを押すとシャットダウンするソフトを作成します。
Raspberry Pi A+は、画面の無いシステムなす。電源をブチ切りするのは避けたいのでこのスイッチを追加しました。
必要なライブラリをインストールします。
npm install onoff
npm install exec-sync
npm install
以下サンプルソフトです。
########################################
var execSync = require(‘exec-sync’);
// button is attaced to pin 20, led to 21
var GPIO = require(‘onoff’).Gpio,
led = new GPIO(21, ‘out’),
button = new GPIO(20, ‘in’, ‘both’);
var interval = setInterval(function()
{
led.read(function (err, value)
{
if (err)
{
throw err;
}
else
{
var val = value === 0 ? 1 : 0;
led.writeSync(val);
}
} );
}, 500);
// define the callback function
function shutdown(err, state)
{
// check the state of the button
// 0 == pressed, 1 == not pressed
if(state == 0)
{
clearInterval(interval);
// turn LED on
led.writeSync(0);
// Shutdown
var poff = execSync(‘sudo shutdown -h now‘);
console.log(opoff);
}
}
// pass the callback function to the
// as the first argument to watch()
button.watch(shutdown);
########################################
ソフトを起動すると500msec毎にLEDが点滅し、ボタンを押すとRaspberry Pi A+がシャットダウンできました。