M5Stack Core2: HTTP クライアント (Get)


http_get/http_get.ino
// ---------------------------------------------------------------
/*
    http_get.ino

                        Sep/03/2021
*/
// ---------------------------------------------------------------
#include <M5Core2.h>
#include <Arduino.h>

#include <WiFiMulti.h>
#include <HTTPClient.h>

WiFiMulti wifiMulti;
HTTPClient http;

const char *ssid = "some-ssid";
const char *password = "some-password";

int count = 0;

// ---------------------------------------------------------------
void setup()
{
    M5.begin();
    wifiMulti.addAP(ssid, password);
    M5.Lcd.print("\nConnecting Wifi...\n");

    delay(3000);
    Serial.println("*** setup *** aaa ***");
    delay(1000);

    String url_target = "https://httpbin.org/get";

    http_get_proc(url_target);

    Serial.println("*** setup ***");
}

// ---------------------------------------------------------------
void loop()
{
    Serial.println("*** loop *** " + String(count));
    M5.Lcd.println("*** loop *** " + String(count));
    delay(5000);
    M5.Lcd.clear();
    delay(5000);
    count++;
}

// ---------------------------------------------------------------
void http_get_proc(String url_target)
{
    if((wifiMulti.run() == WL_CONNECTED)) {
        M5.Lcd.print("[HTTP] begin...\n");
        http.begin(url_target);
        M5.Lcd.print("[HTTP] GET...\n");
        int httpCode = http.GET();
        if(httpCode > 0) {
            M5.Lcd.printf("[HTTP] GET... code: %d\n", httpCode);

            if(httpCode == HTTP_CODE_OK) {
                String payload = http.getString();
                M5.Lcd.println(payload);
                Serial.println(payload);
                }
            }else {
            M5.Lcd.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
            }
        http.end();
    }
    else
        {
        M5.Lcd.print("connect failed");
        }
}

// ---------------------------------------------------------------

シリアルポートの受信は次のコマンドで行います。

cu -s 115200 -l /dev/ttyUSB0