serveur-capteur.ino

Arduino Nano ESP32 · File : serveur-capteur.ino · Language : Arduino · Use case : Exposer une mesure en JSON sur le réseau local

The Nano ESP32 becomes a micro-server: the /mesure route returns the latest ADC reading as JSON, with a 2 Hz anti-refresh guard. A curl, Node-RED or plain browser suffices to consume the data — interoperability without a broker.

Hardware

An Arduino Nano ESP32 (dual-core ESP32-S3, 2.4 GHz Wi-Fi + Bluetooth Low Energy, Nano-compatible physical pinout, native USB, 3.3 V pins only). Nano ESP32 on local WiFi, 0-3.3 V sensor on A0.

Wiring

No network wiring; the IP printed over serial is the API base URL.

How it works

WebServer registers lambdas per route; handleClient() in loop() serves incoming requests. The 500 ms cache shields the ADC from refresh storms.

Running it

Install the Arduino ESP32 Boards package (or follow the official Nano ESP32 guide), select Arduino Nano ESP32, upload. Pins are 3.3 V: never feed 5 V into an input. The serial monitor uses native USB.

Variants

Add a POST route to receive setpoints, or secure with a key in the URL if the network is not trusted.

serveur-capteur.ino

// API JSON locale sur la Nano ESP32 : GET /mesure -> {"adc":1234}
// Reponse a l'auto-refresh d'un tableau de bord ou a un script curl.
#include <WiFi.h>
#include <WebServer.h>

const char SSID[] = "MonReseau";
const char PASS[] = "motdepassewifi";

WebServer serveur(80);
unsigned long dernier = 0;
int derniereValeur = 0;

void setup() {
  Serial.begin(115200);
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) { delay(200); Serial.print('.'); }
  Serial.println(WiFi.localIP());

  serveur.on("/mesure", []() {
    if (millis() - dernier > 500) { // lecture fraiche max 2 Hz
      dernier = millis();
      derniereValeur = analogRead(A0);
    }
    serveur.send(200, "application/json",
                 "{\"adc\":" + String(derniereValeur) + "}");
  });
  serveur.onNotFound([]() { serveur.send(404, "text/plain", "introuvable"); });
  serveur.begin();
  Serial.println(F("API sur /mesure"));
}

void loop() { serveur.handleClient(); }

← Back to the board