🧾 API با JSON روی ESP32 (ArduinoJson)

برد وضعیتش را به شکل JSON می‌دهد و با JSON فرمان می‌گیرد؛ همان زبانی که اپ‌های اینترنت اشیاء با آن حرف می‌زنند.

سطح: چالشی ⭐⭐⭐ · مود: آردوینو (سه‌بعدی + کد)

قطعات لازم

کد کامل پروژه

// ESP32 + ArduinoJson: a small JSON API, the way real IoT apps talk.
//   GET  /api/status  → {"led":false,"pot":1234,"uptime":5,"pins":[4,34]}
//   POST /api/led     ← {"on":true}
// Run it and open the «مرورگر» tab; the Serial Monitor shows the config being read.
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>
#include <AsyncJson.h>

const char* ssid = "MyHome";
const char* password = "12345678";
const int LED = 4;
const int POT = 34;
bool ledOn = false;

AsyncWebServer server(80);

const char index_html[] PROGMEM = R"rawliteral(<!DOCTYPE html>
<html><head><meta name="viewport" content="width=device-width, initial-scale=1">
<style>body{font-family:sans-serif;text-align:center}pre{background:#f4f4f5;padding:8px;text-align:left;display:inline-block}</style></head>
<body><h2>ESP32 JSON API</h2>
<button onclick="led(true)">LED ON</button> <button onclick="led(false)">LED OFF</button>
<button onclick="load()">Refresh</button>
<pre id="out">...</pre>
<script>
function load() {
  fetch("/api/status").then(function (r) { return r.json(); }).then(function (j) {
    document.getElementById("out").innerText = JSON.stringify(j, null, 2);
  });
}
function led(on) {
  fetch("/api/led", { method: "POST", body: JSON.stringify({ on: on }) }).then(load);
}
load();
setInterval(load, 1000);
</script></body></html>
)rawliteral";

// A settings text, as it might come from a file or a server.
const char* config = "{\"room\":\"kitchen\",\"interval\":500,\"pins\":[4,34]}";

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);

  JsonDocument cfg;
  DeserializationError err = deserializeJson(cfg, config);
  if (err) {
    Serial.print("bad config: ");
    Serial.println(err.c_str());
  } else {
    Serial.printf("room %s, every %d ms, LED on pin %d\n",
      cfg["room"].as<const char*>(), cfg["interval"].as<int>(), cfg["pins"][0].as<int>());
    int retries = cfg["retries"] | 3;   // missing key → the default after |
    Serial.printf("retries: %d\n", retries);
  }

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) delay(200);
  Serial.println(WiFi.localIP());

  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request) {
    request->send_P(200, "text/html", index_html);
  });
  server.on("/api/status", HTTP_GET, [](AsyncWebServerRequest *request) {
    JsonDocument doc;
    doc["led"] = ledOn;
    doc["pot"] = analogRead(POT);
    doc["uptime"] = millis() / 1000;
    JsonArray pins = doc["pins"].to<JsonArray>();
    pins.add(LED);
    pins.add(POT);
    String out;
    serializeJson(doc, out);
    request->send(200, "application/json", out);
  });
  // POST with a JSON body: the handler gets it already parsed.
  AsyncCallbackJsonWebHandler* ledHandler = new AsyncCallbackJsonWebHandler("/api/led",
    [](AsyncWebServerRequest *request, JsonVariant &json) {
      JsonObject body = json.as<JsonObject>();
      ledOn = body["on"] | false;
      digitalWrite(LED, ledOn ? HIGH : LOW);
      Serial.println(ledOn ? "LED ON (from JSON)" : "LED OFF (from JSON)");
      request->send(200, "application/json", ledOn ? "{\"led\":true}" : "{\"led\":false}");
    });
  server.addHandler(ledHandler);
  server.begin();
}

void loop() {
}

چطور اجرایش کنم؟

  1. شبیه‌ساز تینکرکد فارسی را باز کن و «مود آردوینو» را انتخاب کن.
  2. از پنل «نمونه‌ها»، «API با JSON روی ESP32 (ArduinoJson)» را بارگذاری کن — مدار و کد با هم می‌آیند.
  3. دکمه‌ی اجرا ▶ را بزن و خروجی Serial و رفتار قطعات را تماشا کن.
  4. حالا کد را تغییر بده — عددها، پین‌ها، ترتیب — و دوباره اجرا کن!
این پروژه را رایگان در شبیه‌ساز اجرا کن 🤖