LoginSignup
0
0

Arduino と node.js で通信してみる

Posted at

1.はじめに

 Arduino UNO と node.js 間で、シリアルポート経由の通信を行うサンプルは、たくさんありますが、試しにやってみると、「serialport.parsers.readline」がエラーになりました。
調べてみると、serialport の使い方が変わっているようです。
 サンプルを書き直して動作するようにしたので、紹介します。
なお、すべての環境や状況で動作を保証するものではありません。

2.環境

 下記のとおり、環境を構築しました。

① node.js
専用ページからダウンロードして、インストールする。

② 作業フォルダ作成
下記フォルダを作成する。

 c:\node

③ node_modules
コマンドプロンプトを起動し、作業をカレントフォルダにした後、モジュールを読み込む。

	cd c:\node
	npm install socket.io 
	npm install serialport
	npm install express

3.ソースコード

メッセージを連携するためのソースコードを作成します。
いずれもUTF-8 で保存してください。

1)Ardunio UNO

 Arduino UNO からは、1秒おきにカウント文字列をシリアルポートへ出力します。
 下記スケッチを適当なフォルダに作成して、Arduino UNO に書き込んでください。

#define DELAY   1000

void  setup() {
  Serial.begin(115200);
  
}

void  loop() {
  static int  cnt = 0;

  Serial.print("count:");
  Serial.print(++cnt);
  Serial.println();

  delay(DELAY);
}

2)node.js

 c:\uno に適当なフォルダを作成し、ソースプログラムを作成します。
 ここでは、sample というフォルダを作成しました。
   c:\node\sample  
  node.js では、Arduino UNO からのテキストを serialport 経由で受け取り、クライアントへ socket.io 経由で転送します。
  

 index.js
 
 // ページの設定
const express  = require('express');
const http     = require('http');
const socketIo = require('socket.io');

const app    = express();
const server = http.Server(app);
const io     = socketIo(server);

const PORT = 8000;

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

// クライアントからの接続待ち
server.listen(PORT, () => {
  console.log(`listening on port ${PORT}`);
});

io.on('connection', (socket) => {
  console.log('user connected');
  socket.on('disconnect', () => {
    console.log('disconnect');
  });
});

// serialport の設定
const { SerialPort }     = require('serialport')
const { ReadlineParser } = require('@serialport/parser-readline')
const port = new SerialPort({ path: 'COM3', baudRate: 115200 })

const parser = port.pipe(new ReadlineParser({ delimiter: '\r\n' }))
parser.on('data', console.log)

// serialport の読み込みと socket.io 経由で送信
port.on("open", () => {
    console.log('open');
    port.on('data', (data) => {
        console.log(data);
        message =  (new TextDecoder).decode(data);      // バイト配列から文字列へ変換する。
        io.emit('receiveMessage', message);
    });
});

3)html

 同一フォルダに、node.js から転送されたメッセージを表示するページを作成します。
 

 index.html
 
 <html>
  <body>
    <h1>serialport & socket.io</h1>
    <ul id="messageList" />

    <script src="/socket.io/socket.io.js"></script>
    <script>

      const socket = io();

      const addMessageList = (message) => {
        const ul = document.getElementById('messageList');
        const li = document.createElement('li');
        const text = document.createTextNode(message);
        li.appendChild(text);
        ul.appendChild(li);
      };

      socket.on('receiveMessage', (message) => {
         addMessageList(message);
      });
    </script>
  </body>
</html>

4.実行

① Arduino UNO の電源を入れます。
② コマンドプロンプトを実行し、作業フォルダをカレントにしてから node.js でプログラムを実行します。

 cd c:\node\sample
 node index.js

③ ブラウザを起動し、ページへアクセスします。

 http://localhost:8000

④ Arduino UNO が出力した文字列が、ブラウザに表示されます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0