mimikakimemo

自分用メモ。

ESP8266 を WiFi につなげる

超特急Web接続! ESPマイコン・プログラム全集』を読んで、製作のための部品を手配中。その間に、WiFi 接続を試したい。現状だとまだ電源が必要なので、ワイヤレスにはならないが…。

WiFi を使うための機能は最初にインストールした ESP8266 Arduino Core に入っているので、追加でインストールする必要はない。公式サイトに WiFi クライアントを使うための quick start があったので、それを参考にした。

#include <ESP8266WiFi.h>

const char *ssid = "my-ssid";
const char *password = "my-password";

WiFiClient client;

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

  // WiFi に接続する
  WiFi.begin(ssid, password);

  // 接続完了まで待つ
  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());

  // WiFi の状態をシリアルモニターに表示
  WiFi.printDiag(Serial);
}

実行結果。ルータの DHCP から IP アドレスが割り当てられている。

f:id:mimikakimemo:20210124154015p:plain

Arduino のスケッチ(.ino ファイル)に自分の SSID とパスワードを書いてしまうと、Git/GitHub での管理が面倒そうなので、本当は環境変数で外から設定できるようにしたい。が、Arduino IDE からではできないっぽい…?

PlatformIO を使えば簡単なのかな? あとで試してみる。

You can inject system environment variable using sysenv as a section. For example, ${sysenv.HOME}.

この前買った ESP8266 開発ボードを電池で動かしたかった

最近触っている ESP8266 の話続き。これを電池で動かすにはどうしたらいいのか?

ESP8266 で検索すると、ESP-WROOM-02開発ボード(ESPr Developer)の情報がよく出てくる。

ESPr Developer(ピンソケット実装済)

ESPr Developer(ピンソケット実装済)

  • メディア: おもちゃ&ホビー

この場合は、単3電池3本をそのまま VIN と GND に繋げばいいらしい。

ただ、今回のキットに入っていた開発ボードは NodeMCU なので、ちょっと違う。ネット上の情報を調べてみたところ…

The best battery for ESP8266 microcontrollers

The NodeMCU has a build in AMS1117 3.3V voltage regulator that transforms the input voltage from the 5V USB connection as well as the voltage of the VIN pin to the stable 3.3V output voltage.

ESP32を電池で動かしてみる (その1) / kghr IT備忘録

その後ネットでいろいろ読んでたら、この”DOIT ESP32 DEVKIT V1 Board” に使われている1117系レギュレータはドロップアウトが1V近くあるのだとか。こちらのデータシートを見てみると、「Operates Down to 1V Dropout」と書いてあり、乾電池で動かすには向いてないのではと思った。

esp8266 - How to power nodemcu devkit using battery - Stack Overflow

The easiest would be to NOT use that devkit but use one with a LiPo connector instead e.g. https://www.adafruit.com/product/2821. An alternative would be to use WeMos D1 minis with a LiPo/battery shield.

If you want to stick to your devkit you "just" have to make sure you feed 3.3V to the 3.3V pin. Since batteries deliver no stable voltage over time you need to place some kind of buck/boost converter (step-down/step-up) between the battery and the module.

You could of course also target the VIN pin which expects 5V but that would be less efficient if you used a LiPo battery. First, the external converter would boost from the LiPo's ~3.7V to 5V. Then the devkits internal converter would have to bring this down to 3.3V again.

Furthermore, if you feed the ESP8266 from batteries you want to pay attention to any power that'd be lost along the way. With the L7805 voltage regulator for example there is a constant 'quiescent' current draw of 6mA. That may be ok if your source is a power adapter but less ideal when it's a battery. Buck/boost converters are more efficient.

うーん…。そもそも NodeMCU の開発ボードは、電池駆動に向いていなかったらしい。

かと言って、ESPr Developer は税込み1,980円なので、少々値段が張ってしまう。複数個作ろうと思うとさらに。以下の記事を参考にしてライターを作れば、ESP-WROOM-02 DIP化キット(650円)に USB 経由でプログラムを書き込めてお手頃になりそう。

DIP というのは Dual Inline Package の略で、IC の両側に脚が出ている形のことだとか。なるほど。

電子工作初心者で分からないことだらけなので、ついでに『超特急Web接続! ESPマイコン・プログラム全集』という本も注文してみた。

ESP8266 と DHT11 で温湿度測定

先月買ったキットに温湿度センサー DHT11 が入っていたので、ESP8266 に温湿度センサー DHT11 をつないで、温度と湿度を測定したい。

今回は以下のサイトを参考にした。

回路図は前者のサイトに従った。

まず、DHT11 を扱うためのライブラリ DHT sensor library をインストールしておく。依存ライブラリは、Arduino IDE からインストールするらしい。

f:id:mimikakimemo:20210118002949p:plain

PratformIOを使うと、依存関係をコード管理できるっぽい?)

DHT11 のデータピンの接続先を、最初は D8 ピンにしていたが、以下のエラーが出てスケッチが書き込めなかった。

Uploading...
esptool.py v2.8
Serial port /dev/tty.usbserial-0001
Connecting........_____....._____....._____....._____.....Traceback (most recent call last):
  File "/Users/***/Library/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/upload.py", line 65, in <module>
    esptool.main(cmdline)
  File "/Users/***/Library/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool/esptool.py", line 2890, in main
    esp.connect(args.before)
  File "/Users/***/Library/Arduino15/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool/esptool.py", line 483, in connect
    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))
esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
An error occurred while uploading the sketch
[Error] Exit with code=1

同じような issue を参考にして D6 ピンに変更したところ、解決した。

今回試したソースは以下の通り。温度と湿度を出力するだけの、ごく簡単なプログラム。

#include "DHT.h"

#define DHTPIN D6     // D6 ピンからセンサーの値を得る
#define DHTTYPE DHT11 // DHT 11 を使う

DHT dht(DHTPIN, DHTTYPE);

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

void loop()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  Serial.println("Temperature: " + String(t, 1) + "°C\tHumidity: " + String(h, 0) + "%");

  delay(2000);
}

出力はこんな感じ。途中で息を吹きかけたので、温度・湿度ともに上昇しているのが分かる。

Temperature: 25.7°C Humidity: 46%
Temperature: 25.7°C    Humidity: 46%
Temperature: 25.7°C    Humidity: 46%
Temperature: 25.7°C    Humidity: 46%
Temperature: 25.7°C    Humidity: 46%
Temperature: 25.7°C    Humidity: 57%
Temperature: 25.8°C    Humidity: 60%
Temperature: 25.7°C    Humidity: 57%
Temperature: 25.7°C    Humidity: 54%
Temperature: 26.1°C    Humidity: 95%
Temperature: 26.7°C    Humidity: 95%
Temperature: 27.1°C    Humidity: 95%
Temperature: 27.3°C    Humidity: 95%
Temperature: 27.6°C    Humidity: 95%
Temperature: 28.1°C    Humidity: 95%

温度の分解能が 1℃ と書かれているサイトもある1が、0.1℃ 単位で値が取得できていた。湿度は 1% 単位。

次は Wifi 経由でデータを送信したい。

ESP8266 の開発を VS Code 上から行う

ESP8266 とか ESP32 とかいうのを使うと、Wifi につながる温湿度センサーなどが安く簡単に作れるらしい。しかも Arduino 互換とのこと。電子工作初心者なのでよくわかっていないが、手持ちのパーツも何もないので、とりあえず「OSOYOO ESP8266ではじめるNodeMCU IoT MQTTプログラミング学習キット」というセットを買ってみた。

Amazon の画像では Ai-Thinker 製のチップ(技適あり)になっているが、届いたのは技適なしのチップだったので、Wifi を使う場合は注意。

今回は、開発環境の構築から。Arduino IDE をそのまま使ってもよいが、VS Code からでも開発できるらしいので、そうしてみる。

  1. Arduino IDE をダウンロードしてインストール。現在のバージョンは 1.8.13
  2. Arduino IDEESP8266 core for Arduino をインストールする。以下の手順はドキュメントのとおり。
    1. Arduino IDE を起動し、Preferences ウィンドウを開く
    2. Additional Boards Manager URLs に https://arduino.esp8266.com/stable/package_esp8266com_index.json と入力し、[OK] をクリックしてウィンドウを閉じる
    3. メニューの Tools > Bord > Boards Manager… をクリックして、Boards Manager ウィンドウを開く
    4. esp8266 を検索し、[Install] ボタンをクリック
  3. Arduino IDE を閉じる
  4. VS Code に MS 製 Arduino 拡張機能をインストール
  5. 画面右下の <Select board type> をクリックして、NodeMCU 1.0 (ESP-12E Module) (esp8266) を選択
    • このあたりのボードの設定は .vscode/arduino.json に保存される様子
  6. USB ケーブルで ESP8266 ボードを接続する
  7. 「ESP8266 が検出されました。ボード設定を変更しますか?」的なトーストが VS Code に出るが、無視する
    • [Yes] を選択した場合、Adafruit Feather HUZZAH ESP8266 (esp8266) に変更されたが、これだとうまく動かない

そして HelloWorld/HelloWorld.ino に、適当なプログラムをコピペした。

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

void loop()
{
    Serial.println("Hello World!");
    delay(5000);
}

コマンドパレット or エディタ右上のアイコンから、Arduino: Upload を実行して ESP8266 にアップロード。結構時間がかかる。完了後、Arduino: Open serial monitor コマンドで Serial monitor を開いたら、Hello World! という出力が確認できた。

次は LED でも。

参考

Haskell に入門するために開発環境を整える

『すごい H 本』こと『すごい Haskell たのしく学ぼう!』をざざっと読んだので、実際に手を動かしてみたい。ということで、開発環境を整える。

Stack

Stack というツールで GHCコンパイラ)のインストールやコードのビルドができるらしい。

まず Homebrew でインストール。

$ brew install stack

新規プロジェクト hello-world を作る。

$ stack new hello-world
Downloading template "new-template" to create project "hello-world" in hello-world/ ...

The following parameters were needed by the template but not provided: author-name
You can provide them in /Users/mimikakimemo/.stack/config.yaml, like this:
templates:
  params:
    author-name: value
Or you can pass each one as parameters like this:
stack new hello-world new-template -p "author-name:value"


The following parameters were needed by the template but not provided: author-email, author-name, category, copyright, github-username
You can provide them in /Users/mimikakimemo/.stack/config.yaml, like this:
templates:
  params:
    author-email: value
    author-name: value
    category: value
    copyright: value
    github-username: value
Or you can pass each one as parameters like this:
stack new hello-world new-template -p "author-email:value" -p "author-name:value" -p "category:value" -p "copyright:value" -p "github-username:value"

Looking for .cabal or package.yaml files to use to init the project.
Using cabal packages:
- hello-world/

Selecting the best among 15 snapshots...

Selected mirror https://s3.amazonaws.com/hackage.fpcomplete.com/
Downloading timestamp
Downloading snapshot
Downloading mirrors
Cannot update index (no local copy)
Downloading index
Updated package index downloaded
Update complete
Populated index cache.
* Matches lts-13.5

Selected resolver: lts-13.5
Initialising configuration using resolver: lts-13.5
Total number of user packages considered: 1
Writing configuration to file: hello-world/stack.yaml
All done.

途中の Downloading index でやたらと時間がかかってフリーズしたかと思ったが、10分ほどで完了した。

$ cd hello-world
$ tree -a
.
├── .gitignore
├── ChangeLog.md
├── LICENSE
├── README.md
├── Setup.hs
├── app/
│   └── Main.hs
├── hello-world.cabal
├── package.yaml
├── src/
│   └── Lib.hs
├── stack.yaml
└── test/
    └── Spec.hs

stack buildGHC のインストールもしてくれる。

$ stack build
Preparing to install GHC to an isolated location.
This will not interfere with any system-level installation.
Downloaded ghc-8.6.3.
Installed GHC.
[1 of 2] Compiling Main             ( /Users/mimikakimemo/.stack/setup-exe-src/setup-mPHDZzAJ.hs, /Users/mimikakimemo/.stack/setup-exe-src/setup-mPHDZzAJ.o )
[2 of 2] Compiling StackSetupShim   ( /Users/mimikakimemo/.stack/setup-exe-src/setup-shim-mPHDZzAJ.hs, /Users/mimikakimemo/.stack/setup-exe-src/setup-shim-mPHDZzAJ.o )
Linking /Users/mimikakimemo/.stack/setup-exe-cache/x86_64-osx/tmp-Cabal-simple_mPHDZzAJ_2.4.0.1_ghc-8.6.3 ...
Building all executables for `hello-world' once. After a successful build of all of them, only specified executables will be rebuilt.
hello-world-0.1.0.0: configure (lib + exe)
Configuring hello-world-0.1.0.0...
hello-world-0.1.0.0: build (lib + exe)
Preprocessing library for hello-world-0.1.0.0..
Building library for hello-world-0.1.0.0..
[1 of 2] Compiling Lib              ( src/Lib.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/Lib.o )
[2 of 2] Compiling Paths_hello_world ( .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/autogen/Paths_hello_world.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/Paths_hello_world.o )
Preprocessing executable 'hello-world-exe' for hello-world-0.1.0.0..
Building executable 'hello-world-exe' for hello-world-0.1.0.0..
[1 of 2] Compiling Main             ( app/Main.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/hello-world-exe-tmp/Main.o )
[2 of 2] Compiling Paths_hello_world ( .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/autogen/Paths_hello_world.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/hello-world-exe-tmp/Paths_hello_world.o )
Linking .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/hello-world-exe ...
hello-world-0.1.0.0: copy/register
Installing library in /Users/mimikakimemo/repos/hello-world/.stack-work/install/x86_64-osx/lts-13.5/8.6.3/lib/x86_64-osx-ghc-8.6.3/hello-world-0.1.0.0-NpaWwN61fJ91LUORGYsB
Installing executable hello-world-exe in /Users/mimikakimemo/repos/hello-world/.stack-work/install/x86_64-osx/lts-13.5/8.6.3/bin
Registering library for hello-world-0.1.0.0..

stack exec <プロジェクト名>-exe で実行できるらしい。

$ stack exec hello-world-exe
someFunc

用意されている app/Main.hs の内容。

module Main where

import Lib

main :: IO ()
main = someFunc

インポートされている src/Lib.hs はこうなっている。

module Lib
    ( someFunc
    ) where

someFunc :: IO ()
someFunc = putStrLn "someFunc"

よって、最終行を someFunc = putStrLn "Hello, world!" に書き換えてビルド・実行すれば、

$ stack build
hello-world-0.1.0.0: unregistering (local file changes: src/Lib.hs)
hello-world-0.1.0.0: build (lib + exe)
Preprocessing library for hello-world-0.1.0.0..
Building library for hello-world-0.1.0.0..
[2 of 2] Compiling Lib              ( src/Lib.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/Lib.o )
Preprocessing executable 'hello-world-exe' for hello-world-0.1.0.0..
Building executable 'hello-world-exe' for hello-world-0.1.0.0..
[1 of 2] Compiling Main             ( app/Main.hs, .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/hello-world-exe-tmp/Main.o ) [Lib changed]
Linking .stack-work/dist/x86_64-osx/Cabal-2.4.0.1/build/hello-world-exe/hello-world-exe ...
hello-world-0.1.0.0: copy/register
Installing library in /Users/mimikakimemo/repos/hello-world/.stack-work/install/x86_64-osx/lts-13.5/8.6.3/lib/x86_64-osx-ghc-8.6.3/hello-world-0.1.0.0-NpaWwN61fJ91LUORGYsB
Installing executable hello-world-exe in /Users/mimikakimemo/repos/hello-world/.stack-work/install/x86_64-osx/lts-13.5/8.6.3/bin
Registering library for hello-world-0.1.0.0..
$ stack exec hello-world-exe
Hello, world!

Hello, world! と表示される。

その他

すごいHaskellたのしく学ぼう!

すごいHaskellたのしく学ぼう!