🌐 روشن کردن LED از صفحه‌ی وب (ESP32)

وب‌سرور ESP32 با دو دکمه‌ی روشن و خاموش؛ صفحه در تب «مرورگر» باز می‌شود.

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

قطعات لازم

کد کامل پروژه

// ESP32 web server: turn an LED on and off from a web page.
// Run it, then open the «مرورگر» (Browser) tab under the code.
#include <WiFi.h>
#include <WebServer.h>

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

WebServer server(80);

String page() {
  String html = "<!doctype html><html><head><meta name='viewport' content='width=device-width'>";
  html += "<style>body{font-family:sans-serif;text-align:center;padding:20px}";
  html += "button{font-size:20px;padding:12px 28px;margin:8px;border-radius:12px;border:0;color:#fff}";
  html += ".on{background:#16a34a}.off{background:#dc2626}</style></head><body>";
  html += "<h2>ESP32 LED</h2>";
  html += "<p id='state'>LED is " + String(ledOn ? "ON" : "OFF") + "</p>";
  html += "<button class='on' onclick=\"go('/on')\">ON</button>";
  html += "<button class='off' onclick=\"go('/off')\">OFF</button>";
  html += "<script>function go(u){fetch(u).then(r=>r.text()).then(t=>document.getElementById('state').innerText=t)}</script>";
  html += "</body></html>";
  return html;
}

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

  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(300);
    Serial.print(".");
  }
  Serial.println();
  Serial.print("Open http://");
  Serial.println(WiFi.localIP());

  server.on("/", []() { server.send(200, "text/html", page()); });
  server.on("/on", []() {
    ledOn = true;
    digitalWrite(LED, HIGH);
    server.send(200, "text/plain", "LED is ON");
  });
  server.on("/off", []() {
    ledOn = false;
    digitalWrite(LED, LOW);
    server.send(200, "text/plain", "LED is OFF");
  });
  server.begin();
}

void loop() {
  server.handleClient();   // without this, the page never answers
}

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

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