Blog::Trapple

技術系のちょっとしたメモとか

Raspberry PiでLチカ(Node.js編)

前の記事Pythonで書いたLチカをNode.jsで書きなおしてみました。

Raspberry PiにシステムワイドなNode.jsをndenvで入れる

ES6を使いたいのでNode.jsはv4以降を入れます。

ライブラリ

さくっと調べた感じだと、Node.jsの場合はgpiowiring-piというライブラリがりました。

gpioの方はI haven't maintained this project for a while nowということでもうメンテしないそうですが、wiring-piに比べて簡素ですぐ使えそうだったので、とりあえずgpioでやってみました。

コード

"use strict";

const gpio = require("gpio");

const channel = 4;
const interval = 50;
let setId;

const gpio4 = gpio.export(channel, {
  direction: "out",
  ready(){
    setId = setInterval(() => {
      this.set();
      setTimeout(() => {
        this.reset(); 
      }, interval);
    }, interval * 2);
  }
});

process.on("SIGINT", () => {
  gpio4.reset();
  clearInterval(setId);
  setTimeout(() => {
    gpio4.unexport();
  }, interval + 1);
  console.log("\nBye!!");
});

この程度であれば言語による優劣は特に無さそうですね。

参考

https://github.com/EnotionZ/GpiO