ITで遊ぶ

ブラウザーとシリアル通信

大きく誤解を招く(少なくとも私は誤解した)ものにJavascriptのSerialとWebUSBがあります。

これらふたつは別物です。WebUSBはとっくに終わったプロジェクトです。にもかかわらず2024年でも紹介記事を書いている人は少なくありません。WebSerialはここにドキュメントがあります。このとおり動きます。(手引書というものも)

しばしば「httpsでないとテストもできない」と書いている人がいますが、それは何年も前の話です。テストはlocalhostで可能です。

以下がサンプルJavascriptです。HTMLにid=statusのテキスト、id=connectButtonというボタン、id=logDataButtonというボタン(最初はdisable)を用意してください。

    let port;
    let reader;

    async function connectToArduino() {
      try {
        port = await navigator.serial.requestPort();
        await port.open({ baudRate: 9600 });

        reader = port.readable.getReader();
        document.getElementById("status").textContent = "Arduino connected!";
        document.getElementById("logDataButton").disabled = false;
      } catch (err) {
        console.error("Failed to connect to Arduino:", err);
      }
    }

    async function logDataToSheets() {
      if (!reader) return;

      try {
        const { value, done } = await reader.read();
        if (done) {
          console.log("Stream closed");
          reader.releaseLock();
          return;
        }

        const sensorData = new TextDecoder().decode(value).trim();
        console.log("Sensor data:", sensorData);
      } catch (err) {
        console.error("Error reading from Arduino or logging data:", err);
      }
    }

    document.getElementById("connectButton").addEventListener("click", connectToArduino);
    document.getElementById("logDataButton").addEventListener("click", logDataToSheets);

Arduino側はこんな感じ。

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  Serial.println("Hello");
  delay(300);
}

これで作るアプリも画面はひとつかふたつで、後はJavascriptでデータを画面に表示することになるでしょうね。
あと、HTMLでダイアログボックス作れればパーフェクトなんですけどねぇ。
いずれにしても、だんだん、CodeIgniterとかRuby On Railsから遠ざかる。。。

関連記事

  1. Googleの検索結果をスプレッドシートに抜く方法

  2. モバイルファースト2

  3. 思想をあらわすプログラミング

  4. web APIサーバーで語られないこと

  5. やっぱりドットインストールは勉強にいい

  6. Google Map APIでとりあえずマーカーを立てる

  7. Perl定石

  8. カラーミー 出荷日のリスト