LoginSignup
68
56

More than 3 years have passed since last update.

ESP32 で無線LANを使う

Last updated at Posted at 2017-09-25

接続するだけなら WiFi.begin() して WiFi.status() で接続状態をみるだけでいい。ちょーかんたん。

HTTP サーバとクライアントを動かしてみた。

HTTP Server にする

アクセスポイントは Aterm で構築し、2.4GHz, WPA/WPA2-PSK(AES) が有効になっている。5GHz は ESP32 が対応していない。

#include <WiFi.h>

const char SSID[] = "WiFi の SSID"
const char PASSWORD[] = "WiFi のパスワード"

WiFiServer server(80);

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

  WiFi.begin(SSID, PASSWORD);
  Serial.print("WiFi connecting");

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

  Serial.println(" connected");

  server.begin();

  Serial.print("HTTP Server: http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");
}

void loop() {
  WiFiClient client = server.available();
  if (client) {
    client.println("Hello World!");
    client.stop();
  }
}

接続されるとシリアルモニタに

WiFi connecting................. connected
HTTP Server: http://192.168.0.11/

のように表示されるので、ブラウザで http://表示されたIPアドレス/ を開く。

HTTP client: GET

ESP32 からの HTTP リクエストを受けるため、同じLAN上の PC で httpd を動かしておく。ここでは GET と POST に対して、リクエストに依らず常に 200, OK を返すサーバを動かすことにする。

simple-httpd.py
#!/usr/bin/env python3

from http.server import HTTPServer, SimpleHTTPRequestHandler


class MyHandler(SimpleHTTPRequestHandler):
    def common_response(self):
        self.send_response(200)
        self.send_header('Content-Type', 'text/plain')
        self.end_headers()
        self.wfile.write(b'OK')

    def do_GET(self):
        self.common_response()

    def do_POST(self):
        content_length = int(self.headers.get('content-length', 0))
        request = self.rfile.read(content_length)  # type: bytes
        print("Request Body: " + request.decode('utf-8'))

        self.common_response()


httpd = HTTPServer(('0.0.0.0', 8000), MyHandler)
httpd.serve_forever()

Python の標準ライブラリしか使っていないので、以下のように実行できる

$ python3 simple-httpd.py

そして ESP32 側のコード。

#include <WiFi.h>
#include <HTTPClient.h>

const char SSID[] = "WiFi の SSID"
const char PASSWORD[] = "WiFi のパスワード"
const char URL[] = "http://<simple-httpd.pyを動かすPCのアドレス>:8000/data";

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

  WiFi.begin(SSID, PASSWORD);
  Serial.print("WiFi connecting");

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

  Serial.println(" connected");
}

void loop() {
  HTTPClient http;
  http.begin(URL);
  int httpCode = http.GET();

  Serial.printf("Response: %d", httpCode);
  Serial.println();
  if (httpCode == HTTP_CODE_OK) {
    String body = http.getString();
    Serial.print("Response Body: ");
    Serial.println(body);
  }

  delay(5000);
}

正しく動いていれば、シリアルモニタに、

Response: 200
Response Body: OK

と5秒ごとに表示され、simple-httpd.py を動かしているコンソールには

192.168.0.4 - - [26/Sep/2017 08:40:36] "GET /data HTTP/1.1" 200 -

のような行が同時に流れていくはず。

HTTP Client: POST

POST も GET とほとんど同じで、http.GET() を http.POST(String payload) に変更するだけ。

// 省略

void loop() {
  HTTPClient http;
  http.begin(URL);
  String requestBody = "Hello World!";
  int httpCode = http.POST(requestBody);

  Serial.printf("Response: %d", httpCode);
  Serial.println();
  if (httpCode == HTTP_CODE_OK) {
    String body = http.getString();
    Serial.print("Response Body: ");
    Serial.println(body);
  }

  delay(5000);
}

simple-httpd.py を動かしているコンソールには GET のときと違って

request: Hello World!

のように ESP32 で指定した文字列が表示される。

なんというか、簡単すぎて逆につまらない...

68
56
2

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
68
56