LoginSignup
2
0

More than 1 year has passed since last update.

WiFi.localIP()をESP_LOGDやsprintfで出力する方法

Posted at

デバイス自身のIPアドレスを得ることができる WiFi.localIP() は、IPAddressクラスを返します。
この情報を利用しようと、例えば Serial.print(WiFi.localIP()); とすれば、IPアドレスが表示されます。

これはIPAddressクラスが Printクラスを継承し、 printTo() が実装されているため、あたかも文字列のように出力できますが、実際は4つのuint8_tで構成されているため、printに対応していない出力では、以下のように表示できません。

コード
ESP_LOGD(TAG, "localIP(): %s", wifi->localIP());
結果
[  5028][D][example.ino:20] setup(): localIP(): ⸮⸮@?⸮⸮⸮=

ESP_LOGDは、ESP32プラットフォーム向けのログライブラリで定義されているマクロで、sprintfのようにフォーマット文字列が利用できます。

対策

toString()c_str() を利用しましょう。

コード
ESP_LOGD(TAG, "localIP(): %s", wifi->localIP().toString().c_str());
結果
[  4829][D][example.ino:20] setup(): localIP(): 192.168.1.102

IPAddressクラスにはStringを返す toString() が実装されています。String自体はフォーマット文字 "%s" では表示できませんが、Stringの c_str()std::string を返すことで、 "%s" で表示できるようになります。

EoT

2
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
2
0