マトリックスLEDをnode.jsで動かす

raspberry pi上のnode.jsでマトリクスLEDを動かしてみました。

公式サイトなどを参考に作成しました。
マトリックスLEDに文字描画 - blog.obniz.io
MatrixLED_MAX7219 | JS Parts Library | obniz

1. node.jsをインストール

Node-REDの公式サイトに従い、インストールします。
Running on Raspberry Pi : Node-RED

 
次のコマンドを実行

bash <(curl -sL https://raw.githubusercontent.com/node-red/linux-installers/master/deb/update-nodejs-and-nodered)

 

2. node-canvasをインストール

GitHub - Automattic/node-canvas: Node canvas is a Cairo backed Canvas implementation for NodeJS.

 
次のコマンドを実行

sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev

続けて次のコマンドを実行

$ npm install canvas

3. node-canvasを使って実装

現在時刻を表示します。

const Obniz=require("obniz");
const { createCanvas } = require('canvas');
 
const obniz = new Obniz("xxxx-xxxx");
 
obniz.onconnect = async function () {
         const matrix = obniz.wired("MatrixLED_MAX7219", {vcc:11, gnd:10, din:9, cs:8, clk:7});
         matrix.init(8*4, 8);
         matrix.brightness(1);
 
         var canvas = new createCanvas(matrix.width, matrix.height);
         ctx = canvas.getContext('2d');
 
         x = matrix.width;
         var nowDate = LoadTime();
  
         obniz.repeat(async function(){
                 ctx.fillStyle = "black";
                 ctx.fillRect(0, 0, matrix.width, matrix.height);
                 ctx.fillStyle = "white";
                 ctx.font = "9px Noto Sans Mono CJK JP";
                 ctx.fillText(nowDate, x, 7);
                 x--;
                 matrix.draw(ctx);
         }, 1000/10)
 }
 
 var now = new Date();
 function LoadTime() {
         var Year = now.getFullYear();
         var Month = now.getMonth()+1;
         var Date = now.getDate();
         var Hour = now.getHours();
         var Min = now.getMinutes();
         var Sec = now.getSeconds(); 
         var nowDate = Month + "/" + Date + " " + Hour + ":" + Min;
         return nowDate;
 }