🛠 Se connecter au Wi-Fi et interroger une API HTTP

M5StickC Plus2 (M5Stack) — ESP32-PICO-V3-02 "stick" wearable kit (SKU K016-P2) · intermediaire · Schéma : IMG-m5stack-stick-c-plus-2-intermediaire-3-m5stick-c2-wifi-http.svg — M5StickC Plus2 reliée par une onde Wi-Fi 2,4 GHz à un routeur puis à un serveur HTTP, l'écran affichant la température récupérée en JSON.

Objectives

Connect the M5StickC Plus2 to a 2.4 GHz Wi-Fi network (the ESP32-PICO-V3-02 chip does not support 5 GHz; the v2's 3D antenna offers better range than the v1) and query an HTTP API using a GET request with the HTTPClient library, then display a value extracted from the JSON.

Hardware

Complete code

// Wi-Fi 2.4 GHz + requete HTTP GET (reconnexion auto par minute)
#include <M5Unified.h>
#include <WiFi.h>
#include <HTTPClient.h>

const char* SSID = "VOTRE_WIFI_24GHZ";
const char* PASS = "motdepasse";
const char* URL  = "http://ip.jsontest.com/";   // renvoie {"ip": "..."}

void setup {
  auto cfg = M5.config;
  M5.begin(cfg);
  Serial.begin(115200);
  M5.Display.setRotation(1);
  M5.Display.setTextSize(1);
  M5.Display.setTextColor(TFT_WHITE, TFT_BLACK);
  M5.Display.printf("WiFi %s...\n", SSID);
  WiFi.mode(WIFI_STA);                  // station uniquement
  WiFi.begin(SSID, PASS);
  while (WiFi.waitForConnectResult != WL_CONNECTED) {
    M5.Display.println("echec, nouvelle tentative...");
    delay(3000);
  }
  M5.Display.printf("IP: %s\n", WiFi.localIP.toString.c_str);
}

void boucleHttp {
  HTTPClient http;
  http.begin(URL);
  int code = http.GET;
  M5.Display.setCursor(0, 40);
  if (code == HTTP_CODE_OK) {
    String corps = http.getString;
    int i = corps.indexOf("\"ip\": \"") + 7;   // extraction JSON maison
    String ip = (i > 6) ? corps.substring(i, corps.indexOf('"', i)) : "?";
    M5.Display.setTextColor(TFT_GREEN, TFT_BLACK);
    M5.Display.printf("IP publique: %s", ip.c_str);
    Serial.println(corps);
  } else {
    M5.Display.setTextColor(TFT_RED, TFT_BLACK);
    M5.Display.printf("HTTP erreur %d", code);
  }
  http.end;
}

void loop {
  M5.update;
  if (M5.BtnA.wasPressed) boucleHttp;   // A = relancer une requete
  if (WiFi.status != WL_CONNECTED) WiFi.reconnect;
  vTaskDelay(50 / portTICK_PERIOD_MS);
}

Expected verification

After connecting, the local IP is displayed; pressing A triggers a GET request and the public IP returned by the API is displayed in green. The serial monitor shows the raw JSON body.

Common errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials