🛠 Serveur web embarqué : YunServer, YunClient et pages dynamiques

Arduino Yún · avance · IMG-yun-avance-7-yun-serveur-web-yunserver.svg — Yún avec un serveur HTTP dessiné dans la partie Linux : navigateur connecté sur le port 5555, requête GET /temperature, réponse JSON ; le Bridge relie le serveur au 32U4 qui lit un capteur sur A1.

Objectives

Move beyond the generic REST API to write YOUR OWN web server: the YunServer library opens a TCP port on the Linux side (via the avrbridge daemon), and YunClient represents each connection. You will serve an HTML page and a JSON endpoint read by a real sensor, understanding that HTTP is handled by Linux while the 32U4 remains the only component touching the pins.

Hardware

Complete Code

// Serveur HTTP minimal sur le port 5555 : page + JSON capteur.
#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

YunServer serveur;
const uint8_t CAPTEUR = A1;

void setup {
  Bridge.begin;
  serveur.listenOnLocalhost;   // écoute côté Linux
  serveur.begin;
}

void loop {
  YunClient client = serveur.accept;
  if (!client) return;                 // aucune connexion en attente
  process(client);
  client.stop;                       // toujours fermer la connexion
}

void process(YunClient client) {
  String methode = client.readStringUntil('\t');     // GET /temperature HTTP/1.1
  String chemin  = client.readStringUntil('\t');
  client.readStringUntil('\r');                      // reste de la ligne HTTP
  client.readStringUntil('\n');
  // Vide les en-têtes jusqu'à la ligne vide (sinon ils seront lus comme le corps)
  String ligne;
  while ((ligne = client.readStringUntil('\n')).length > 1) { }

  if (chemin == "/temperature") {
    int v = analogRead(CAPTEUR);
    client.print(F("HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n"
                   "Connection: close\r\n\r\n"));
    client.print(F("{\"capteur\":A1,\"brut\":"));
    client.print(v);
    client.println(F(",\"unite\":\"adc10\"}"));
  } else if (chemin == "/") {
    client.print(F("HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n"
                   "Connection: close\r\n\r\n"
                   "<h1>Yun vivante</h1>"
                   "<p><a href='/temperature'>/temperature</a></p>"));
  } else {
    client.print(F("HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n"));
  }
}

Expected Verification

http://arduino.local:5555/temperature returns a JSON with the sensor reading (0–1023), refreshed on each request. curl -v shows the Connection: close header and a clean connection. Open two tabs: YunServer serializes requests — a blocking request (poorly placed sleep) freezes the site, hence the requirement for short handlers.

Common Errors

Other tutorials for this board

Code examples for this board

← Back to the board 🛠 All tutorials