Ví dụ ESP32 WebSlider Hướng dẫn Giao diện Điều khiển Hai Thanh Trượt
Tổng quan
Ví dụ WebSlider cung cấp hai thanh trượt độc lập có thể truy cập thông qua trình duyệt web. Được thiết kế cho nền tảng giáo dục ESP32 với khả năng analog được cải tiến, các tính năng điều khiển chính xác và các mô-đun giáo dục tích hợp để học PWM và điện tử analog. Mỗi thanh trượt cung cấp giá trị từ 0-255, làm cho chúng phù hợp cho điều khiển PWM, điều chỉnh độ sáng, điều khiển tốc độ động cơ và bất kỳ ứng dụng nào yêu cầu các giá trị điều khiển có đặc tính analog.
Tính năng
Hai thanh trượt đôi: Hai thanh trượt độc lập (khoảng 0-255 cho mỗi thanh)
Giá trị thời gian thực: Cập nhật giá trị tức thì qua giao tiếp WebSocket
Tương thích PWM: Giá trị 8-bit (0-255) hoàn hảo cho các hàm analogWrite()
Phản hồi trực quan: Hiển thị giá trị theo thời gian thực cho từng thanh trượt
Nút thiết lập trước: Giá trị thiết lập trước nhanh cho các cấu hình phổ biến
Hỗ trợ cảm ứng và chuột: Hoạt động trên máy tính để bàn, máy tính bảng và thiết bị di động
Thiết kế đáp ứng: Phù hợp với các kích thước màn hình khác nhau
Lưu giá trị: Các thanh trượt nhớ vị trí cuối cùng khi tải lại trang
Kết nối bảng ESP32 với máy tính của bạn bằng cáp USB.
Mở Arduino IDE trên máy tính của bạn.
Chọn bảng ESP32 phù hợp (ví dụ ESP32 Dev Module) và cổng COM.
Đi tới biểu tượng Thư viện ở thanh bên trái của Arduino IDE.
Tìm kiếm "DIYables ESP32 WebApps", sau đó tìm thư viện DIYables ESP32 WebApps do DIYables.
Nhấn nút Cài đặt để cài đặt thư viện.
Bạn sẽ được yêu cầu cài đặt một số phụ thuộc thư viện khác.
Nhấn nút Cài đặt Tất cả để cài đặt tất cả các phụ thuộc thư viện.
Trong Arduino IDE, hãy vào File Examples DIYables ESP32 WebApps WebSlider ví dụ, hoặc sao chép đoạn mã ở trên và dán vào trình soạn thảo của Arduino IDE
/* * DIYables WebApp Library - Web Slider Example * * This example demonstrates the Web Slider feature: * - Two independent sliders (0-255) * - Real-time value monitoring * - Template for hardware control * * Hardware: ESP32 Boards * * Setup: * 1. Update WiFi credentials below * 2. Upload the sketch to your Arduino * 3. Open Serial Monitor to see the IP address * 4. Navigate to http://[IP_ADDRESS]/webslider */#include <DIYables_ESP32_Platform.h>#include <DIYablesWebApps.h>// WiFi credentials - UPDATE THESE WITH YOUR NETWORKconstchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// Create WebApp server and page instancesESP32ServerFactory serverFactory;DIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;DIYablesWebSliderPage webSliderPage;// Current slider valuesint slider1Value = 64; // Default 25%int slider2Value = 128; // Default 50%voidsetup() {Serial.begin(9600);delay(1000);// TODO: Initialize your hardware pins hereSerial.println("DIYables ESP32 WebApp - Web Slider Example");// Add home and web slider pageswebAppsServer.addApp(&homePage);webAppsServer.addApp(&webSliderPage);// Optional: Add 404 page for better user experiencewebAppsServer.setNotFoundPage(DIYablesNotFoundPage());// Start the WebApp serverif (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) {while (1) {Serial.println("Failed to start WebApp server!");delay(1000); } }// Set up slider callback for value changes webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) {// Store the received values slider1Value = slider1; slider2Value = slider2;// Print slider values (0-255)Serial.println("Slider 1: " + String(slider1) + ", Slider 2: " + String(slider2));// TODO: Add your control logic here based on slider values// Examples:// - Control PWM: analogWrite(LED_PIN, slider1);// - Control servos: servo.write(map(slider1, 0, 255, 0, 180));// - Control motor speed: analogWrite(MOTOR_PIN, slider2);// - Control brightness: strip.setBrightness(slider1);// - Send values via Serial, I2C, SPI, etc. });// Set up callback for config requests (when client requests current values) webSliderPage.onSliderValueToWeb([]() { webSliderPage.sendToWebSlider(slider1Value, slider2Value);Serial.println("Web client requested values - Sent: Slider1=" + String(slider1Value) + ", Slider2=" + String(slider2Value)); });}voidloop() {// Handle WebApp server communicationswebAppsServer.loop();// TODO: Add your main application code heredelay(10);}
Cấu hình thông tin đăng nhập WiFi trong mã bằng cách cập nhật các dòng này:
Nhấn nút Tải lên trên Arduino IDE để tải mã lên ESP32
Mở Serial Monitor
Xem kết quả trên Serial Monitor. Nó trông như dưới đây
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
ESP32 Dev Module
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
DIYables WebApp - Web Slider Example
INFO: Added app /
INFO: Added app /web-slider
DIYables WebApp Library
Platform: ESP32
Network connected!
IP address: 192.168.0.2
HTTP server started on port 80
Configuring WebSocket server callbacks...
WebSocket server started on port 81
WebSocket URL: ws://192.168.0.2:81
WebSocket server started on port 81
==========================================
DIYables WebApp Ready!
==========================================
📱 Web Interface: http://192.168.0.2
🔗 WebSocket: ws://192.168.0.2:81
📋 Available Applications:
🏠 Home Page: http://192.168.0.2/
🎚️ Web Slider: http://192.168.0.2/web-slider
==========================================
Ln 11, Col 1
ESP32 Dev Module on COM15
2
Nếu bạn không thấy gì, hãy khởi động lại bo mạch ESP32.
Ghi chú địa chỉ IP được hiển thị và nhập địa chỉ này vào thanh địa chỉ của trình duyệt web trên điện thoại thông minh hoặc PC của bạn.
Ví dụ: http://192.168.0.2
Bạn sẽ thấy trang chủ như hình dưới đây:
Nhấp vào liên kết Web Slider, bạn sẽ thấy giao diện người dùng của ứng dụng Web Slider như dưới đây:
Hoặc bạn cũng có thể truy cập trang trực tiếp bằng địa chỉ IP theo sau là /web-slider. Ví dụ: http://192.168.0.2/web-slider
Hãy thử di chuyển hai thanh trượt để điều khiển các giá trị analog (0-255) và xem phản hồi thời gian thực trong Trình theo dõi Serial.
Tùy biến sáng tạo - Chỉnh sửa mã nguồn cho dự án của bạn
Thanh trượt 1: Thanh trượt điều khiển đầu tiên có hiển thị giá trị (0-255)
Thanh trượt 2: Thanh trượt điều khiển thứ hai có hiển thị giá trị (0-255)
Hiển thị giá trị: Các giá trị số theo thời gian thực cho cả hai thanh trượt
Nút thiết lập trước: Truy cập nhanh đến các giá trị phổ biến (0%, 25%, 50%, 75%, 100%)
Điều khiển các thanh trượt
Máy tính để bàn (Điều khiển chuột)
Nhấp chuột và kéo: Nhấp chuột vào tay nắm của thanh trượt và kéo để điều chỉnh giá trị
Vị trí nhấp chuột: Nhấp chuột bất cứ đâu trên thanh trượt để nhảy tới giá trị đó
Điều khiển tinh chỉnh: Sử dụng những chuyển động chuột nhỏ để điều chỉnh chính xác
Điện thoại di động / Máy tính bảng (Điều khiển cảm ứng)
Chạm và Kéo: Chạm vào đầu kéo của thanh trượt và kéo đến vị trí mới
Chạm Vị Trí: Chạm lên thanh trượt để thiết lập giá trị
Điều khiển mượt mà: Việc kéo bằng ngón tay cho phép thay đổi giá trị một cách mượt mà
Khoảng giá trị
Mỗi thanh trượt cung cấp:
Giá trị tối thiểu: 0 (0% - tắt hoàn toàn)
Giá trị tối đa: 255 (100% - cường độ tối đa)
Độ phân giải: 256 bước rời rạc (độ chính xác 8-bit)
Tương thích PWM: Sử dụng trực tiếp với hàm analogWrite()
Ví dụ về Lập trình
Trình xử lý thanh trượt cơ bản
voidsetup() {// Set up slider callback for value changes webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) {// Store the received values slider1Value = slider1; slider2Value = slider2;// Print slider values (0-255)Serial.println("Slider 1: " + String(slider1) + ", Slider 2: " + String(slider2));// Add your control logic here });}
Điều khiển độ sáng LED
// Pin definitions for PWM LEDsconstint LED1_PIN = 9; // PWM pin for first LEDconstint LED2_PIN = 10; // PWM pin for second LEDvoidsetup() {// Configure LED pins as outputspinMode(LED1_PIN, OUTPUT);pinMode(LED2_PIN, OUTPUT);// Set initial brightnessanalogWrite(LED1_PIN, slider1Value);analogWrite(LED2_PIN, slider2Value); webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) {// Store values slider1Value = slider1; slider2Value = slider2;// Control LED brightness directly (0-255 PWM)analogWrite(LED1_PIN, slider1);analogWrite(LED2_PIN, slider2);Serial.println("LED1 Brightness: " + String(slider1) +", LED2 Brightness: " + String(slider2)); });}
void setupThresholdControl() { webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) { slider1Value = slider1; slider2Value = slider2;// Threshold-based control for discrete outputsconstint LOW_THRESHOLD = 85; // 33%constint MEDIUM_THRESHOLD = 170; // 66%// Control digital outputs based on slider 1 thresholdsif (slider1 < LOW_THRESHOLD) {// Low level: Turn off all outputsdigitalWrite(2, LOW);digitalWrite(3, LOW);digitalWrite(4, LOW); } elseif (slider1 < MEDIUM_THRESHOLD) {// Medium level: Turn on first outputdigitalWrite(2, HIGH);digitalWrite(3, LOW);digitalWrite(4, LOW); } else {// High level: Turn on all outputsdigitalWrite(2, HIGH);digitalWrite(3, HIGH);digitalWrite(4, HIGH); }// Use slider 2 for analog PWM controlanalogWrite(9, slider2); });}
Hệ thống Giá trị Đặt trước
// Predefined preset valuesconstint PRESETS[][2] = { {0, 0}, // Preset 0: Both off {64, 128}, // Preset 1: Low/Medium {128, 128}, // Preset 2: Both medium {255, 128}, // Preset 3: High/Medium {255, 255} // Preset 4: Both maximum};void applyPreset(int presetNumber) {if (presetNumber >= 0 && presetNumber < 5) { slider1Value = PRESETS[presetNumber][0]; slider2Value = PRESETS[presetNumber][1];// Update hardwareanalogWrite(9, slider1Value);analogWrite(10, slider2Value);// Send updated values to web interface webSliderPage.sendToWebSlider(slider1Value, slider2Value);Serial.println("Applied preset " + String(presetNumber) +": " + String(slider1Value) + ", " + String(slider2Value)); }}void setupPresetSystem() {// You could trigger presets based on other inputs// For example, reading digital pins for preset buttons webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) { slider1Value = slider1; slider2Value = slider2;// Your normal slider handlinganalogWrite(9, slider1);analogWrite(10, slider2); });}voidloop() { server.loop();// Check for preset trigger conditions// Example: Read buttons connected to digital pinsstaticbool lastButton = false;bool currentButton = digitalRead(7); // Preset button on pin 7if (currentButton && !lastButton) { // Button pressedstaticint currentPreset = 0; applyPreset(currentPreset); currentPreset = (currentPreset + 1) % 5; // Cycle through presets } lastButton = currentButton;}
Các ví dụ về tích hợp phần cứng
Điều khiển dải LED
// For WS2812B or similar addressable LED strips// (requires additional libraries like FastLED or Adafruit NeoPixel)constint LED_STRIP_PIN = 6;constint NUM_LEDS = 30;void setupLEDStrip() {// Initialize LED strip (depends on library used) webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) { slider1Value = slider1; slider2Value = slider2;// Slider 1 controls brightness (0-255)// Slider 2 controls color temperature or hueuint8_t brightness = slider1;uint8_t hue = slider2;// Update LED strip (example with conceptual functions)// strip.setBrightness(brightness);// strip.fill(CHSV(hue, 255, 255));// strip.show();Serial.println("LED Strip - Brightness: " + String(brightness) +", Hue: " + String(hue)); });}
Sử dụng thanh trượt để giới hạn tốc độ và joystick để điều khiển hướng.
// Global speed limit from slidersintmaxSpeed = 255;// In WebSlider callbackwebSliderPage.onSliderValueFromWeb([](int slider1, int slider2) {maxSpeed = slider1; // Use slider 1 as global speed limit});// In WebJoystick callbackwebJoystickPage.onJoystickValueFromWeb([](int x, int y) {// Scale joystick values by slider-controlled speed limitint scaledX = map(x, -100, 100, -maxSpeed, maxSpeed);int scaledY = map(y, -100, 100, -maxSpeed, maxSpeed); controlRobot(scaledX, scaledY);});
Kết hợp với WebDigitalPins
Sử dụng thanh trượt để điều khiển PWM và các chân số để bật/tắt:
webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) {// Only apply PWM if corresponding digital pins are ONif (webDigitalPinsPage.getPinState(2)) {analogWrite(9, slider1); } else {analogWrite(9, 0); }if (webDigitalPinsPage.getPinState(3)) {analogWrite(10, slider2); } else {analogWrite(10, 0); }});
Video hướng dẫn
Video demo bên dưới sử dụng đoạn mã bên dưới:
/* * Mã ESP32 này được phát triển bởi newbiely.vn * Mã ESP32 này được cung cấp để sử dụng công khai, không có ràng buộc. * Để xem hướng dẫn chi tiết và sơ đồ kết nối, vui lòng truy cập: * https://newbiely.vn/tutorials/esp32/diyables-esp32-web-apps-web-slider *//* * DIYables WebApp Library - Web Slider Example * * This example demonstrates the Web Slider feature: * - Two independent sliders (0-255) * - Real-time value monitoring * - Template for hardware control * * Hardware: ESP32 Boards * * Setup: * 1. Update WiFi credentials below * 2. Upload the sketch to your Arduino * 3. Open Serial Monitor to see the IP address * 4. Navigate to http://[IP_ADDRESS]/webslider */#include <DIYables_ESP32_Platform.h>#include <DIYablesWebApps.h>#include <ESP32Servo.h>Servo servo1, servo2;// WiFi credentials - UPDATE THESE WITH YOUR NETWORKconstchar WIFI_SSID[] = "YOUR_WIFI_SSID";constchar WIFI_PASSWORD[] = "YOUR_WIFI_PASSWORD";// Create WebApp server and page instancesESP32ServerFactory serverFactory;DIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;DIYablesWebSliderPage webSliderPage;// Current slider valuesint slider1Value = 64; // Default 25%int slider2Value = 128; // Default 50%voidsetup() {Serial.begin(9600);delay(1000);// TODO: Initialize your hardware pins here servo1.attach(26); servo2.attach(27);Serial.println("DIYables ESP32 WebApp - Web Slider Example");// Add home and web slider pageswebAppsServer.addApp(&homePage);webAppsServer.addApp(&webSliderPage);// Optional: Add 404 page for better user experiencewebAppsServer.setNotFoundPage(DIYablesNotFoundPage());// Start the WebApp serverif (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) {while (1) {Serial.println("Failed to start WebApp server!");delay(1000); } }// Set initial positions servo1.write(map(slider1Value, 0, 255, 0, 180)); servo2.write(map(slider2Value, 0, 255, 0, 180)); webSliderPage.onSliderValueFromWeb([](int slider1, int slider2) { slider1Value = slider1; slider2Value = slider2;// Map slider values (0-255) to servo angles (0-180°)int angle1 = map(slider1, 0, 255, 0, 180);int angle2 = map(slider2, 0, 255, 0, 180);// Move servos to calculated positions servo1.write(angle1); servo2.write(angle2);Serial.println("Servo1: " + String(angle1) + "°, Servo2: " + String(angle2) + "°"); });// Set up callback for config requests (when client requests current values) webSliderPage.onSliderValueToWeb([]() { webSliderPage.sendToWebSlider(slider1Value, slider2Value);Serial.println("Web client requested values - Sent: Slider1=" + String(slider1Value) + ", Slider2=" + String(slider2Value)); });}voidloop() {// Handle WebApp server communicationswebAppsServer.loop();// TODO: Add your main application code heredelay(10);}
Các bước tiếp theo
Sau khi thành thạo ví dụ WebSlider, hãy thử:
WebJoystick - Để điều khiển theo hướng hai chiều (2D)
WebDigitalPins - Để điều khiển bật/tắt rời rạc
WebMonitor - Để gỡ lỗi giá trị của thanh trượt
MultipleWebApps - Kết hợp thanh trượt với các điều khiển khác
Hỗ trợ
Để được hỗ trợ thêm:
Kiểm tra tài liệu tham khảo API
Truy cập các bài hướng dẫn DIYables: https://esp32io.com/tutorials/diyables-esp32-webapps