WebDigitalPins 예제는 Arduino의 모든 디지털 핀을 제어하고 모니터링하기 위한 웹 기반 인터페이스를 제공합니다. ESP32 교육 플랫폼용으로 설계되어 향상된 GPIO 기능, 확장된 핀 구성, 디지털 전자학습을 위한 내장 교육 기능이 포함되어 있습니다. 핀을 켜고 끄고, 핀의 상태를 실시간으로 모니터링하며, 직관적인 웹 인터페이스를 통해 다수의 핀에 대해 일괄 작업을 수행할 수 있습니다.
"DIYables ESP32 WebApps"를 검색한 다음 DIYables에서 제공하는 DIYables ESP32 WebApps 라이브러리를 찾습니다.
Install 버튼을 클릭하여 라이브러리를 설치합니다.
다른 라이브러리 의존성 설치를 요청받게 됩니다.
모든 라이브러리 의존성을 설치하려면 Install All 버튼을 클릭하십시오.
Arduino IDE에서 File 예제 DIYables ESP32 WebApps WebDigitalPins 예제로 이동하거나, 위의 코드를 복사하여 Arduino IDE의 에디터에 붙여넣으세요
/* * DIYables WebApp Library - Web Digital Pins Example * * This example demonstrates the Web Digital Pins feature with automatic command handling: * - Control output pins 0-13 via web interface * - Monitor input pins 0-13 in real-time * - Individual pin ON/OFF control for outputs * - Real-time pin status feedback for inputs * - Bulk operations (All ON, All OFF, Toggle All) for outputs * * 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]/webdigitalpins */#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 using platform abstractionESP32ServerFactory serverFactory;DIYablesWebAppServerwebAppsServer(serverFactory, 80, 81);DIYablesHomePage homePage;DIYablesWebDigitalPinsPage webDigitalPinsPage;// Array to store the state of each digital pin (0-13). Index corresponds to pin number.int pinStates[16] = { 0 }; // Initialize all states to LOW (0)voidsetup() {Serial.begin(9600);delay(1000);Serial.println("DIYables ESP32 WebApp - Web Digital Pins Example");// Add home and digital pins pageswebAppsServer.addApp(&homePage);webAppsServer.addApp(&webDigitalPinsPage);// Optional: Add 404 page for better user experiencewebAppsServer.setNotFoundPage(DIYablesNotFoundPage());// Pin Configuration Examples:// Method 1: Enable specific pins individually for output control webDigitalPinsPage.enablePin(0, WEB_PIN_OUTPUT); // Enable pin 0 (TX - use with caution) webDigitalPinsPage.enablePin(1, WEB_PIN_OUTPUT); // Enable pin 1 (RX - use with caution) webDigitalPinsPage.enablePin(2, WEB_PIN_OUTPUT); webDigitalPinsPage.enablePin(3, WEB_PIN_OUTPUT); webDigitalPinsPage.enablePin(4, WEB_PIN_OUTPUT);//webDigitalPinsPage.enablePin(5, WEB_PIN_OUTPUT); // Comment/uncomment to disable/enable//webDigitalPinsPage.enablePin(6, WEB_PIN_OUTPUT); // Comment/uncomment to disable/enable webDigitalPinsPage.enablePin(13, WEB_PIN_OUTPUT); // Enable pin 13 (built-in LED)// Method 2: Enable pins for input monitoring webDigitalPinsPage.enablePin(8, WEB_PIN_INPUT); webDigitalPinsPage.enablePin(9, WEB_PIN_INPUT);//webDigitalPinsPage.enablePin(10, WEB_PIN_INPUT); // Comment/uncomment to disable/enable//webDigitalPinsPage.enablePin(11, WEB_PIN_INPUT); // Comment/uncomment to disable/enable// Method 3: Enable all pins at once (uncomment to use)// for (int pin = 0; pin <= 13; pin++) {// webDigitalPinsPage.enablePin(pin, WEB_PIN_OUTPUT); // or WEB_PIN_INPUT as needed// }// Method 4: Enable pins in a range using for loop (uncomment to use)// for (int pin = 7; pin <= 11; pin++) {// webDigitalPinsPage.enablePin(pin, WEB_PIN_OUTPUT); // or WEB_PIN_INPUT as needed// }// Initialize enabled pinsint outputPins[] = { 0, 1, 2, 3, 4, 13 }; // Note: Pins 0,1 are TX/RX - use with cautionfor (int i = 0; i < 6; i++) {int pin = outputPins[i];pinMode(pin, OUTPUT);digitalWrite(pin, LOW); pinStates[pin] = LOW; }int inputPins[] = { 8, 9 };for (int i = 0; i < 2; i++) {int pin = inputPins[i];pinMode(pin, INPUT); // Use INPUT_PULLUP if needed pinStates[pin] = digitalRead(pin); }// Start the WebApp serverif (!webAppsServer.begin(WIFI_SSID, WIFI_PASSWORD)) {while (1) {Serial.println("Failed to start WebApp server!");delay(1000); } }// Return the current state to display on Web App webDigitalPinsPage.onPinRead([](int pin) {return pinStates[pin]; // Return the current state of the pin// You can implement custom read logic here if needed });// Handle the control request from Web App (for output pins) webDigitalPinsPage.onPinWrite([](int pin, int state) {digitalWrite(pin, state); pinStates[pin] = state;// You can implement custom control logic here if needed });// Handle pin mode change requests (optional) webDigitalPinsPage.onPinModeChange([](int pin, int mode) {if (mode == WEB_PIN_OUTPUT) {pinMode(pin, OUTPUT);digitalWrite(pin, LOW); pinStates[pin] = LOW; } elseif (mode == WEB_PIN_INPUT) {pinMode(pin, INPUT); // or INPUT_PULLUP as needed pinStates[pin] = digitalRead(pin); }// You can implement custom mode change logic here if needed });}voidloop() {// Handle WebApp server communicationswebAppsServer.loop();// Monitor input pins for real-time updatesstaticunsignedlong lastInputCheck = 0;if (millis() - lastInputCheck > 100) { // Check every 100ms lastInputCheck = millis();// Check input pins for changes and send real-time updatesint inputPins[] = { 8, 9 };for (int i = 0; i < 2; i++) {int pin = inputPins[i];int currentState = digitalRead(pin);if (currentState != pinStates[pin]) { pinStates[pin] = currentState;// Send real-time update to web clients webDigitalPinsPage.updatePinState(pin, currentState); } } }// Add your main application code heredelay(10);}
Message (Enter to send message to 'ESP32 Dev Module' on 'COM15')
New Line
9600 baud
WebSocket client connected from: 192.168.0.5
New WebSocket connection established
WebSocket message received: SLIDER:GET_VALUES
WebSocket client connected from: 192.168.0.5
New WebSocket connection established
WebSocket message received: SLIDER:64,128
DIYables WebApp - Web Digital Pins Example
INFO: Added app /
INFO: Added app /web-digital-pins
DEBUG: Enabling pin 0 with mode OUTPUT
DEBUG: Enabling pin 1 with mode OUTPUT
DEBUG: Enabling pin 2 with mode OUTPUT
DEBUG: Enabling pin 3 with mode OUTPUT
DEBUG: Enabling pin 4 with mode OUTPUT
DEBUG: Enabling pin 13 with mode OUTPUT
DEBUG: Enabling pin 8 with mode INPUT
DEBUG: Enabling pin 9 with mode INPUT
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/
📟 Digital Pins: http://192.168.0.2/web-digital-pins
==========================================
Ln 11, Col 1
ESP32 Dev Module on COM15
2
아무 것도 보이지 않는 경우 ESP32 보드를 재부팅하십시오.
표시된 IP 주소를 확인해 두고, 이 주소를 스마트폰 또는 PC의 웹 브라우저 주소창에 입력하십시오.
예: http://192.168.0.2
아래 이미지와 같은 홈 페이지가 표시됩니다:
Web Digital Pins 링크를 클릭하면 아래와 같은 Web Digital Pins 앱의 UI가 표시됩니다:
또한 IP 주소에 /web-digital-pins를 붙여 페이지에 직접 접속할 수도 있습니다. 예를 들어: http://192.168.0.2/web-digital-pins
핀 버튼을 클릭해 디지털 핀을 ON/OFF로 제어하고, 명령에 응답하는 내장 LED(핀 13)를 관찰해 보세요.
창의적인 맞춤화 - 코드를 프로젝트에 맞게 조정
예제는 창의적인 프로젝트의 필요에 맞게 핀을 구성하는 다양한 방법을 보여줍니다:
2. 핀 설정 구성
예제는 핀을 구성하는 다양한 방법을 보여줍니다:
방법 1: 특정 핀 활성화
// Enable individual pins for output controlwebDigitalPinsPage.enablePin(2, WEB_PIN_OUTPUT); // Pin 2 as outputwebDigitalPinsPage.enablePin(3, WEB_PIN_OUTPUT); // Pin 3 as outputwebDigitalPinsPage.enablePin(4, WEB_PIN_INPUT); // Pin 4 as input
방법 2: 핀 범위 활성화
// Enable a range of pins for output controlwebDigitalPinsPage.enableOutputPins(2, 13); // Pins 2-13 as outputs
방법 3: 모든 핀 활성화
// Enable all pins 0-13 for control (use with caution for pins 0,1)webDigitalPinsPage.enableAllPins();
4. 스케치 업로드
I. ESP32 보드를 선택하세요: Tools → Board → ESP32
I. 올바른 포트를 선택하세요: Tools → Port → [당신의 ESP32 포트]
I. 업로드 버튼을 클릭하세요
5. IP 주소 가져오기
도구 → 시리얼 모니터 열기
시리얼 속도(baud rate)를 9600으로 설정
ESP32가 WiFi에 연결될 때까지 기다리세요
표시된 IP 주소를 기록해 두세요(예: 192.168.1.100)
6. 디지털 핀 인터페이스에 접근하기
웹 브라우저를 열고 다음 위치로 이동하세요:
http://[ARDUINO_IP_ADDRESS]/digital-pins
예시: http://192.168.1.100/digital-pins
사용하는 방법
핀 제어 인터페이스
웹 인터페이스는 구성된 모든 핀을 다음과 같이 표시합니다:
핀 번호: ESP32 핀(0-13)을 표시
현재 상태: ON(초록) 또는 OFF(빨강) 표시
제어 버튼: 핀 상태를 토글하려면 클릭
핀 타입: 입력(Input) 또는 출력(Output)으로 구성되었는지 표시
개별 핀 제어
핀 켜기: 핀 버튼이 "OFF"로 표시될 때 클릭하세요
핀 끄기: 핀 버튼이 "ON"으로 표시될 때 클릭하세요
모니터 상태: 핀 버튼은 현재 상태를 표시하도록 자동으로 업데이트됩니다
대량 작업
여러 핀을 한 번에 제어하려면 일괄 제어 버튼을 사용하십시오:
모두 켜짐
구성된 모든 출력 핀을 HIGH 상태로 설정합니다
입력 핀은 영향을 받지 않습니다
연결된 모든 장치를 테스트하는 데 유용합니다
모두 끄기
구성된 모든 출력 핀을 LOW 상태로 설정합니다
입력 핀은 영향을 받지 않습니다
모든 출력을 안전하게 비활성화하는 방법
모두 선택
모든 출력 핀의 상태를 반전시킵니다
ON 핀은 OFF가 되고, OFF 핀은 ON이 됩니다
흥미로운 조명 효과를 만듭니다
실시간 모니터링
핀 상태가 WebSocket을 통해 자동으로 업데이트됩니다
코드에서 이루어진 변경 내용이 웹 인터페이스에 반영됩니다
여러 사용자가 동시에 동일한 ESP32를 모니터링할 수 있습니다
하드웨어 연결
출력 핀 예시
LED 제어
Arduino Pin → LED (with resistor) → Ground
Pin 2 → LED Anode → 220Ω Resistor → Ground
Pin 3 → LED Anode → 220Ω Resistor → Ground
Sensor Signal → ESP32 Pin
PIR Sensor → Pin 10
Ultrasonic → Pin 11 (Echo)
코드 커스터마이징
핀 변경 콜백 추가
핀의 상태가 변경될 때 모니터링:
voidsetup() {// Set callback for pin state changes webDigitalPinsPage.onPinChange([](int pin, bool state) {Serial.print("Pin ");Serial.print(pin);Serial.print(" changed to: ");Serial.println(state ? "HIGH" : "LOW");// Add your custom logic hereif (pin == 13 && state == HIGH) {Serial.println("Built-in LED turned ON!"); } });}
사용자 정의 핀 초기화
시작 시 특정 핀을 원하는 상태로 설정:
voidsetup() {// Initialize pins to specific states webDigitalPinsPage.setPinState(2, HIGH); // Turn on pin 2 webDigitalPinsPage.setPinState(3, LOW); // Turn off pin 3// Configure pin modespinMode(4, INPUT_PULLUP); // Pin 4 as input with pull-uppinMode(5, OUTPUT); // Pin 5 as output}
voidsetup() { webDigitalPinsPage.enablePin(2, WEB_PIN_OUTPUT); // LED webDigitalPinsPage.enablePin(3, WEB_PIN_INPUT); // PIR sensorpinMode(3, INPUT);}voidloop() {if (digitalRead(3) == HIGH) { // Motion detected webDigitalPinsPage.setPinState(2, HIGH); // Turn on LEDdelay(5000); // Keep on for 5 seconds webDigitalPinsPage.setPinState(2, LOW); // Turn off LED }}
온도 제어 팬
voidloop() {float temperature = getTemperature(); // Your temperature reading functionif (temperature > 25.0) { webDigitalPinsPage.setPinState(4, HIGH); // Turn on fan } else { webDigitalPinsPage.setPinState(4, LOW); // Turn off fan }}