2026年5月6日水曜日

kallumajs and color-oled/kaluma esp8266-http-client and node express ドラフト

color oled 成功(ssd1306)

npm i https://github.com/niklauslee/ssd1306 してnode_modules/examples/

に入りkaluma flash ./ex _128x128.js --bundleで成功 うれしい

ーーーーーーーーーーーーーーーーーーーーーーーーーー

https://javascript.plainenglish.io/physical-computing-with-javascript-8-8-connecting-to-internet-151ba3dfce59にある例題  

まずdht,exp8266-httpをnpm install(kalumajsサイトpackages参考)

kalumaはfirwareこわれやすいのでkaluma flash ./index.js --bundle で止まる時は入れ直す

node app.jsで頓死おこるならPC再起動ポート番号も変更せんといかんときもある

--------nodejs-------app.js--------node app.js--で先に起動してサーバipを決定する!

これはちゃんとうごくがportが閉じられんときもある、別ブログで対策をかいた

const express = require('express');

const ip = require('ip');

const app = express();

const addr = ip.address();

const port = 3000;

let temperature = '0.0';

let humidity = '0';

app.get('/update', (req, res) => {

  if (req.query.t) temperature = req.query.t;

  if (req.query.h) humidity = req.query.h;

  res.status(200).send('OK');

});


app.get('/', (req, res) => {

  res.setHeader('Content-Type', 'text/html');

  res.send(`

<html>

  <body>

   <h1>${temperature}</h1>

   <h1>${humidity}</h1>

  </body>

</html>

  `);

});


app.listen(port, () => {

  console.log(`Server running at http://${addr}:${port}`);

});

-----kalumajs--index.js---flash後にkaluma shellで.load----だがうごきが悪い。。。。

ごりごりatをチェーンするバージョンはパス!

簡単な方をえらぶ、チャットくんがつくったのは以下

const { DHT } = require('dht');

const { ESP8266HTTPClient } = require('esp8266-http-client');

// 設定

const WIFI_SSID = 'Buffalo-2G-8340';

const WIFI_PASSWORD = '636nsa535ds3v';

const ADDRESS = '192.168.11.8';

const PORT = '3001';

// DHT11

const dht = new DHT(15, DHT.DHT11);

// ESP8266

const esp = new ESP8266HTTPClient();

function start() {

  setInterval(() => {

    try {

      dht.read();

      let t = dht.temperature.toFixed(1);

      let h = dht.humidity.toFixed(0);

      console.log(`TEMP=${t} HUM=${h}`);

      const url =

        `http://${ADDRESS}:${PORT}/update?t=${t}&h=${h}`;

      console.log(url);

      esp.http(url)

        .then(res => {

          console.log('send ok');

        })

        .catch(err => {

          console.log('http error');

          console.log(err);

        });

    } catch(err) {

      console.log('dht error');

      console.log(err);

    }

  }, 10000);

}

// WiFi接続

esp.wifi(WIFI_SSID, WIFI_PASSWORD)

  .then(() => {

    console.log('wifi connected');

    start();

  })

  .catch(err => {

    console.log('wifi connect failed');

    console.log(err);

  });



0 件のコメント:

コメントを投稿