Ví dụ ESP32 WebJoystick Hướng dẫn điều khiển joystick ảo
Tổng quan
Ví dụ WebJoystick tạo giao diện joystick ảo có thể truy cập từ bất kỳ trình duyệt web nào. Được thiết kế cho ESP32 nền tảng giáo dục với khả năng robotics được nâng cao, tính năng điều khiển động cơ tích hợp và tích hợp liền mạch với các mô-đun giáo dục robot. Hoàn hảo để điều khiển robot, phương tiện hoặc bất kỳ hệ thống nào yêu cầu đầu vào vị trí hai chiều.
Tính năng
Joystick ảo: Điều khiển joystick tương tác qua giao diện web
Tọa độ thời gian thực: Giá trị X/Y từ -100 đến +100 cho điều khiển chính xác
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
Chế độ trả về tự động có thể cấu hình: Tùy chọn cho joystick trả về vị trí giữa khi được thả
Điều khiển độ nhạy: Độ nhạy có thể điều chỉnh để ngăn chặn cập nhật quá mức
Phản hồi trực quan: Hiển thị vị trí thời gian thực và các giá trị tọa độ
Giao tiếp WebSocket: Phản hồi tức thì mà không làm mới trang
Vị trí trung tâm: Chỉ báo vị trí trung tâm rõ ràng cho điều khiển ở trạng thái trung lập
Kết nối bo mạch 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 bo mạch ESP32 phù hợp (ví dụ ESP32 Dev Module) và cổng COM.
Đi tới biểu tượng Libraries ở 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 cung cấp.
Nhấp nút Install để 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ấp vào nút Cài đặt Tất cả để cài đặt tất cả các phụ thuộc thư viện.
Trên Arduino IDE, hãy vào File Examples DIYables ESP32 WebApps WebJoystick ví dụ, hoặc sao chép mã ở trên và dán nó vào trình soạn thảo của Arduino IDE
/* * DIYables WebApp Library - Web Joystick Example * * This example demonstrates the Web Joystick feature: * - Interactive joystick control via web interface * - Real-time X/Y coordinate values (-100 to +100) * - Control pins based on joystick position * * 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]/webjoystick */#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 instances// MEMORY SAFETY FIX: Use static factory to avoid stack object lifetime issuesstatic ESP32ServerFactory serverFactory; // Static ensures lifetime matches programDIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;// Configure joystick with autoReturn=false and sensitivity=5 (minimum 5% change to trigger updates)DIYablesWebJoystickPage webJoystickPage(false, 5);// Variables to store current joystick valuesint currentJoystickX = 0;int currentJoystickY = 0;voidsetup() {Serial.begin(9600);delay(1000);// TODO: initialize your hardware pins hereSerial.println("DIYables ESP32 WebApp - Web Joystick Example");// Add home and web joystick pageswebAppsServer.addApp(&homePage);webAppsServer.addApp(&webJoystickPage);// 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 joystick callback for position changes webJoystickPage.onJoystickValueFromWeb([](int x, int y) {// Store the received values currentJoystickX = x; currentJoystickY = y;// Print joystick position values (-100 to +100)Serial.println("Joystick - X: " + String(x) + ", Y: " + String(y));// TODO: Add your control logic here based on joystick position// Examples:// - Control motors: if (x > 50) { /* move right */ }// - Control servos: servo.write(map(y, -100, 100, 0, 180));// - Control LEDs: analogWrite(LED_PIN, map(abs(x), 0, 100, 0, 255));// - Send commands to other devices via Serial, I2C, SPI, etc. });// Optional: Handle requests for current joystick values (when web page loads) webJoystickPage.onJoystickValueToWeb([]() {// Send the stored joystick values back to the web client webJoystickPage.sendToWebJoystick(currentJoystickX, currentJoystickY);Serial.println("Web client requested values - Sent to Web: X=" + String(currentJoystickX) + ", Y=" + String(currentJoystickY)); });// You can change configuration at runtime:// webJoystickPage.setAutoReturn(false); // Disable auto-return// webJoystickPage.setSensitivity(10.0); // Only send updates when joystick moves >10% (less sensitive)}voidloop() {// Handle WebApp server communicationswebAppsServer.loop();// TODO: Add your main application code heredelay(10);}
Cấu hình thông tin xác thực WiFi trong mã nguồn 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
Kiểm tra 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 Joystick Example
INFO: Added app /
INFO: Added app /web-joystick
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 Joystick: http://192.168.0.2/web-joystick
==========================================
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 nhớ đị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 Joystick, bạn sẽ thấy giao diện người dùng của ứng dụng Web Joystick 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 kèm theo /web-joystick. Ví dụ: http://192.168.0.2/web-joystick
Hãy thử điều khiển joystick ảo bằng cách nhấp và kéo trên vùng joystick và quan sát các giá trị tọa độ X/Y (-100 đến +100) trong Serial Monitor.
Tùy chỉnh sáng tạo - Điều chỉnh mã cho dự án của bạn
2. Cấu hình cài đặt Joystick
Joystick có thể được cấu hình với các tham số khác nhau:
Cấu hình cơ bản
// Create joystick with default settings (autoReturn=true, sensitivity=1)DIYablesWebJoystickPage webJoystickPage;
Cấu hình nâng cao
// Create joystick with custom settings// autoReturn=false: Joystick stays at last position when released// sensitivity=5: Only send updates when movement > 5%DIYablesWebJoystickPage webJoystickPage(false, 5);
Cách sử dụng Joystick
Các điều khiển giao diện web
Giao diện joystick cung cấp:
Bảng điều khiển joystick: Khu vực điều khiển hình tròn cho đầu vào cảm ứng/chuột
Chỉ báo vị trí: Hiển thị vị trí joystick hiện tại
Hiển thị tọa độ: Giá trị X/Y theo thời gian thực (-100 đến +100)
Điểm giữa: Tham chiếu trực quan cho vị trí trung lập
Vận hành Joystick
Máy tính để bàn (Điều khiển chuột)
Nhấp và kéo: Nhấp vào joystick và kéo để di chuyển
Buông: Joystick trả về vị trí trung tâm (nếu autoReturn=true)
Vị trí nhấp chuột: Nhấp trực tiếp để đặt vị trí của joystick
Đ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 joystick và kéo ngón tay để di chuyển
Đa chạm: Một ngón tay để điều khiển chính xác
Thả: Tự động trả về vị trí trung tâm (nếu được bật)
Hệ tọa độ
Joystick cung cấp các tọa độ trong một hệ tọa độ Cartesian chuẩn:
Trục X: -100 (ở bên trái hoàn toàn) đến +100 (ở bên phải hoàn toàn)
Trục Y: -100 (ở dưới hoàn toàn) đến +100 (ở trên hoàn toàn)
Trung tâm: X=0, Y=0 (vị trí trung tính)
Các góc: Các vị trí chéo cung cấp giá trị X/Y kết hợp
Ví dụ Lập trình
Trình xử lý Joystick cơ bản
voidsetup() {// Set up joystick callback for position changes webJoystickPage.onJoystickValueFromWeb([](int x, int y) {// Store the received values currentJoystickX = x; currentJoystickY = y;// Print joystick position valuesSerial.println("Joystick - X: " + String(x) + ", Y: " + String(y));// Add your control logic here });}
void setupRobotCar() {// Motor driver pinspinMode(2, OUTPUT); // Left motor direction 1pinMode(3, OUTPUT); // Left motor direction 2pinMode(4, OUTPUT); // Right motor direction 1pinMode(5, OUTPUT); // Right motor direction 2pinMode(9, OUTPUT); // Left motor PWMpinMode(10, OUTPUT); // Right motor PWM webJoystickPage.onJoystickValueFromWeb([](int x, int y) {// Tank drive calculationint leftMotor = y + (x / 2); // Forward/back + steeringint rightMotor = y - (x / 2); // Forward/back - steering// Constrain to valid range leftMotor = constrain(leftMotor, -100, 100); rightMotor = constrain(rightMotor, -100, 100);// Control motors setMotorSpeed(9, 2, 3, leftMotor); // Left motor setMotorSpeed(10, 4, 5, rightMotor); // Right motor });}void setMotorSpeed(int pwmPin, int dir1Pin, int dir2Pin, intspeed) {if (speed > 0) {digitalWrite(dir1Pin, HIGH);digitalWrite(dir2Pin, LOW);analogWrite(pwmPin, map(speed, 0, 100, 0, 255)); } elseif (speed < 0) {digitalWrite(dir1Pin, LOW);digitalWrite(dir2Pin, HIGH);analogWrite(pwmPin, map(-speed, 0, 100, 0, 255)); } else {digitalWrite(dir1Pin, LOW);digitalWrite(dir2Pin, LOW);analogWrite(pwmPin, 0); }}
Sử dụng joystick để điều hướng và các thanh trượt để điều chỉnh tốc độ và cường độ.
// Use joystick for direction, sliders for speed limitswebJoystickPage.onJoystickValueFromWeb([](int x, int y) {intmaxSpeed = getSliderValue(); // From WebSliderint 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 các vị trí của joystick để kích hoạt trạng thái của các chân số:
webJoystickPage.onJoystickValueFromWeb([](int x, int y) {// Activate pins based on joystick quadrants webDigitalPinsPage.setPinState(2, x > 50); // Right quadrant webDigitalPinsPage.setPinState(3, x < -50); // Left quadrant webDigitalPinsPage.setPinState(4, y > 50); // Upper quadrant webDigitalPinsPage.setPinState(5, y < -50); // Lower quadrant});
Các bước tiếp theo
Sau khi nắm vững ví dụ WebJoystick, hãy thử:
WebSlider - Để điều khiển analog bổ sung
WebDigitalPins - Để điều khiển bật/tắt rời rạc
WebMonitor - Để gỡ lỗi các giá trị của joystick
MultipleWebApps - Kết hợp joystick 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