[ESP32]固定IPアドレスでWifi接続する方法

ESP32

固定IPアドレスでWifiアクセスポイントに接続する方法

サンプルコード(コピペで動作)

固定IPアドレスを使用して無線ルーターに接続するサンプルコード。

使用API:WiFi.config() / WiFi.begin()

#include <WiFi.h>

const char* ssid     = "xxxxxxxx";
const char* password = "xxxxxxxx";
const IPAddress ip(192, 168, 11, 52);
const IPAddress gateway(192, 168, 11, 1);
const IPAddress subnet(255, 255, 255, 0);
const IPAddress dns1(192, 168, 11, 1);

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

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  if (!WiFi.config(ip,gateway,subnet,dns1)){
      Serial.println("Failed to configure!");
  }
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop()
{
  // put your main code here, to run repeatedly:
}

[ssid]と[password]の内容は変更します。

const char* ssid     = "xxxxxx";
const char* password = "xxxxxx";

固定IPアドレスを取得する場合は、WiFi.config()を使用します。

  if (!WiFi.config(ip,gateway,subnet,dns1)){
      Serial.println("Failed to configure!");
  }

引数

local_ipESP-WROOM-32に割り当てるIPアドレス
gatewayゲートウェイのIPアドレス
subnetサブネットマスク
dns1プライマリDNSサーバのIPアドレス。(オプション)
dns2セカンダリDNSサーバのIPアドレス。(オプション)

dns1,dns2はオプションのため指定しなくても良いですが、外部と通信する場合は必要になります。今回はdns1のみ指定しています。

Wi-Fi API - - — Arduino ESP32 latest documentation

確認方法

以下のようにシリアルモニタに表示されれば、接続完了です。

まとめ

今後Webサーバを立てた時など、利用者がIPアドレスを知りたいシステムを作る場合に便利だと思います。

また、家庭内の無線LAN接続機器を管理する上でも、常時接続しているものは固定IPアドレスにしていると何かと便利です。

Wifi切断時に自動で接続させる方法はこちら👇

コメント

タイトルとURLをコピーしました