SimpleWiFiServer

はじめに

WebブラウザからHTTPサーバにアクセスして、ESP-WROOM-32に接続したLEDを、点灯・消灯します。

点灯: http://yourAddress/H、消灯: http://yourAddress/L です。

LEDは、5番ピンに接続している想定です。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
 WiFi Web Server LED Blink

 A simple web server that lets you blink an LED via the web.
 This sketch will print the IP address of your WiFi Shield (once connected)
 to the Serial monitor. From there, you can open that address in a web browser
 to turn on and off the LED on pin 5.

 If the IP address of your shield is yourAddress:
 http://yourAddress/H turns the LED on
 http://yourAddress/L turns it off

 This example is written for a network using WPA2 encryption. For insecure
 WEP or WPA, change the Wifi.begin() call and use Wifi.setMinSecurity() accordingly. 

 Circuit:
 * WiFi shield attached
 * LED attached to pin 5

 created for arduino 25 Nov 2012
 by Tom Igoe

ported for sparkfun esp32 
31.01.2017 by Jan Hendrik Berlin
 
 */

#include <WiFi.h>

const char* ssid     = "yourssid";
const char* password = "yourpasswd";

WiFiServer server(80);
 

ssidとpasswordは、自分の環境に合わせて設定してください。

WiFiServer型の変数serverを定義します。ポート番号80で待ち受けます。

setup()

35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
void setup()
{
    Serial.begin(115200);
    pinMode(5, OUTPUT);      // set the LED pin mode

    delay(10);

    // We start by connecting to a WiFi network

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

    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());
    
    server.begin();

}
 

pinMode()により、5番ピン(LEDを接続しているピン)を出力に設定します。

WiFi.begin()により、ssidで指定したアクセスポイントに接続します。この際のパスフレーズは、passwordです。WiFiは、WiFi.cppで定義されている変数です。

WiFi.status()は、現在の接続状態を返却します。アクセスポイントに接続しているときは、WL_CONNECTEDが返ってきます。

WiFi.localIP()は、現在割り当てられているIPアドレスを返却します。

最後に、server.begin()で、HTTPサーバを開始します。

loop()

 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
int value = 0;

void loop(){
 WiFiClient client = server.available();   // listen for incoming clients

  if (client) {                             // if you get a client,
    Serial.println("New Client.");           // print a message out the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    while (client.connected()) {            // loop while the client's connected
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        if (c == '\n') {                    // if the byte is a newline character

          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println();

            // the content of the HTTP response follows the header:
            client.print("Click <a href=\"/H\">here</a> to turn the LED on pin 5 on.<br>");
            client.print("Click <a href=\"/L\">here</a> to turn the LED on pin 5 off.<br>");

            // The HTTP response ends with another blank line:
            client.println();
            // break out of the while loop:
            break;
          } else {    // if you got a newline, then clear currentLine:
            currentLine = "";
          }
        } else if (c != '\r') {  // if you got anything else but a carriage return character,
          currentLine += c;      // add it to the end of the currentLine
        }

        // Check to see if the client request was "GET /H" or "GET /L":
        if (currentLine.endsWith("GET /H")) {
          digitalWrite(5, HIGH);               // GET /H turns the LED on
        }
        if (currentLine.endsWith("GET /L")) {
          digitalWrite(5, LOW);                // GET /L turns the LED off
        }
      }
    }
    // close the connection:
    client.stop();
    Serial.println("Client Disconnected.");
  }
}

65行目に定義されているvalueは、特に利用していないようです。

68行目で、server.available()により、WiFiクライアントからの接続を取得し、WiFiClient型の変数clientに代入します。クライアントから接続がない場合は、if (client)が、falseになります。以降は、clientを用いて、WiFiクライアントとやり取りを行います。

server.available()は、UNIXのselect()に似たようなイメージです。クライアントからの接続があるまでブロックするかもと思い、実際に試してみましたが、クライアントからの接続がない場合もブロックしませんでした。

client.connected()は、clientとの接続状態を返します。接続されている場合(trueが返ってきた場合)は、client.available()で、読み込み可能なバイト数を取得します。1文字以上読み取りできる場合は、client.read()で1文字読みます。

client.print()/client.println()で、HTTPリクエストを書き込みます。WiFiClientは、Printクラスを継承しているので、Serialと同じように、print()などを利用することができます。

104行目等の、currentLine.endsWith()で、送信された文字列が、“GET /H"あるいは"GET /L"で終わるかを確認し、条件が成立した場合は、digitalWrite()を利用して、ピンの出力を変化させます。

最後に、client.stop()を呼び出して、WiFi接続を停止します。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

November 1, 2022

inserted by FC2 system