📈 نمودار زندهی سنسور با EventSource روی ESP32
برد هر عدد تازهی پتانسیومتر را خودش برای صفحه میفرستد (Server-Sent Events) و صفحه نمودار زنده میکشد.
سطح: چالشی ⭐⭐⭐ · مود: آردوینو (سهبعدی + کد)
قطعات لازم
کد کامل پروژه
// ESP32 + Server-Sent Events: the board PUSHES each new reading to the page,
// and the page draws a live chart. Turn the knob and watch the line move.
// Run it and open the «مرورگر» tab.
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
const char* ssid = "MyHome";
const char* password = "12345678";
const int POT = 34; // GPIO34: input-only, 12-bit ADC (0..4095)
unsigned long lastSend = 0;
AsyncWebServer server(80);
AsyncEventSource events("/events");
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}canvas{border:1px solid #ccc;background:#fff}</style></head>
<body><h2>Live knob chart</h2>
<p>Value: <b id="v">-</b> <small id="st" style="color:#888">connecting...</small></p>
<canvas id="c" width="320" height="160"></canvas>
<script>
var data = [];
var c = document.getElementById("c"), g = c.getContext("2d");
function draw() {
g.clearRect(0, 0, c.width, c.height);
g.strokeStyle = "#0284c7"; g.lineWidth = 2; g.beginPath();
for (var i = 0; i < data.length; i++) {
var x = i * (c.width / 59), y = c.height - data[i] / 4095 * c.height;
if (i === 0) g.moveTo(x, y); else g.lineTo(x, y);
}
g.stroke();
}
var src = new EventSource("/events");
src.onopen = function () { document.getElementById("st").innerText = "live"; };
src.addEventListener("hello", function (e) { console.log("board says", e.data); });
src.addEventListener("pot", function (e) {
var v = Number(e.data);
document.getElementById("v").innerText = v;
data.push(v); if (data.length > 60) data.shift();
draw();
});
</script></body></html>
)rawliteral";
void setup() {
Serial.begin(115200);
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);
});
events.onConnect([](AsyncEventSourceClient *client) {
Serial.println("a page is listening");
client->send("hi!", "hello", millis(), 1000);
});
server.addHandler(&events);
server.begin();
}
void loop() {
if (millis() - lastSend > 300) {
lastSend = millis();
int value = analogRead(POT);
events.send(String(value).c_str(), "pot", millis());
}
}
چطور اجرایش کنم؟
- شبیهساز تینکرکد فارسی را باز کن و «مود آردوینو» را انتخاب کن.
- از پنل «نمونهها»، «نمودار زندهی سنسور با EventSource روی ESP32» را بارگذاری کن — مدار و کد با هم میآیند.
- دکمهی اجرا ▶ را بزن و خروجی Serial و رفتار قطعات را تماشا کن.
- حالا کد را تغییر بده — عددها، پینها، ترتیب — و دوباره اجرا کن!