1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ESP32で再接続する方法(認証Webサイトの場合)

Posted at

現在ESP32でWeb認証機能を設けたシステムを構築しているんだが、
APがなにかの問題で再起動した場合、
WiFiに再接続する機能を設けていなかったのでその機能をつけた。

そこで問題が発生だ!!

void loop() {
  //接続が切れた場合の処理
  if((WiFi.status() != WL_CONNECTED)) {
    chkCount += 1 ;       // カウント
    if (chkCount > 10) {  // 10回目(5秒) で切断/再接続
      ESP.restart() ;     // 再起動
    }
  }else{
      chkCount = 0;
  }
  delay(500);
}

以上の処理で5秒間接続が行われない場合は、ESPをリスタートするようにしたのだが、
この機能を追加すると何故かWeb認証機能で正しいID、PASSを入力しても
認証ができない。

なぜだ?!

調べてみたら認証機能を設けている場合「delay(500);」を入れると正常に
認証ができないみたい。。。

しょうがないので以下の方法で接続が切れたイベントを取得して、
ESPをリスタートかけ、APに再接続するようにした。


// ■■■■■■■■■
// WiFiが切断された時の処理
// ■■■■■■■■■

void WiFiStationDisconnected(WiFiEvent_t event, WiFiEventInfo_t info){
  ESP.restart() ;     // 再起動
}

void setup(){
    //WiFi設定
    IPAddress ip(192,168,0,99);
    IPAddress gateway(255,255,255,0);
    IPAddress netmask(192.168.0.1);
    
    WiFi.mode(WIFI_STA);              //ルータ接続モード
    WiFi.config(ip, gateway,netmask); //ルータ接続設定
    WiFi.disconnect(true,true);       //既に接続が合った場合、解除
    delay(1000);
    WiFi.onEvent(WiFiStationDisconnected, SYSTEM_EVENT_STA_DISCONNECTED); //接続解除イベント
    WiFi.begin(buf.ssid, buf.pass);   //ルータ接続処理
    int lpcnt=0;
    int lpcnt2=0;
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);                            // 0.5秒毎にチェック
      lpcnt += 1 ;                           // カウント
      if (lpcnt > 10) {                      // 10回目(5秒) で切断/再接続
        WiFi.disconnect(true,true) ;         // 
        WiFi.begin(buf.ssid, buf.pass); 
        lpcnt = 0 ;                          //
        lpcnt2 += 1 ;                        // 再接続の回数をカウント
      }                                      //
      if (lpcnt2 > 3) {                      // 3回 接続できなければ、
        ESP.restart() ;                      // 再起動
      }                                      //
      Serial.print(".");                     //
    }
  
    // Print ESP Local IP Address
    Serial.println(WiFi.localIP());

}

void loop() {

}

しかし、なぜ「delay(500);」がloopのところにあったら正常に動作できないかは、
謎のままです。。。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?