지난 강좌에 이어서 이번에는 버튼을 좀더 예쁘게 만들겠습니다.
https://jooduino.tistory.com/5
ESP32 웹서버 만들기 - 버튼 추가
지난 강좌에 이어서 이번에는 웹페이지에 버튼을 만들고 모듈의 내부에 있는 LED를 ON/OFF 제어를 하겠습니다. https://jooduino.tistory.com/3 ESP32 웹서버 만들기 'Hello world' ESP32의 최대 장점인 와이파이를
jooduino.tistory.com
먼저, 버튼을 예쁘게 만들려면 버튼에 대한 CSS 파일을 만들어야 합니다.
HTML, CSS, JAVASCRIPT에 대해 공부를 하시면 좀더 이해가 빠르고 쉽게 만들 수 있습니다.
일단, CSS에 대해서 모르시면 아래 파일을 다운 받아서 사용하시면 됩니다.
'my.css' 파일은 버튼을 예쁘게 만들어 주는 파일입니다. 이 파일을 다운로드 하여 SPIFFS에 넣어 주시면 됩니다.
https://jooduino.tistory.com/6
ESP32 SPIFFS 사용하기
ESP32가 아닌 일반적으로 사용하던 ATMega328의 아두이노를 사용했을땐 데이터를 저장하기 위해서 내부의 EEPROM을 이용하였습니다. EEPROM에 간단한 데이터는 저장하기 편리하지만, 파일을 저장할 수
jooduino.tistory.com
지난 강좌 소스코드에 몇가 추가 하면 됩니다.
1. SPIFFS 사용하기위한 헤더파일 추가
#include "SPIFFS.h"
2. HTML 파일 수정
const char index_html[] PROGMEM = R"==(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ESP32 테스트 페이지</title>
<link href="my.css" type="text/css" rel="stylesheet" crossorigin="anonymous">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
</style>
</head>
<body>
<h2>LED</h2>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)">
<span class="slider round"></span>
</label>
<script>
function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
if(element.checked){ xhr.open("GET", "/on", true); }
else { xhr.open("GET", "/off", true); }
xhr.send();
}
</script>
</body>
</html>
)==";
3. SPIFFS 초기화
if( !SPIFFS.begin( true ) )
{
Serial.println( F("An Error has occurred while mounting SPIFFS") );
return;
}
4. CSS 파일 연결
// SPIFFS의 CSS파일 연결
server.on( "/my.css", HTTP_GET, [] (AsyncWebServerRequest *request )
{
request->send( SPIFFS, "/my.css", "text/css" );
});
전체 소스코드
#include <WiFi.h>
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include "SPIFFS.h"
AsyncWebServer server(80);
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
const char index_html[] PROGMEM = R"==(
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ESP32 테스트 페이지</title>
<link href="my.css" type="text/css" rel="stylesheet" crossorigin="anonymous">
<style>
html {font-family: Arial; display: inline-block; text-align: center;}
</style>
</head>
<body>
<h2>LED</h2>
<label class="switch">
<input type="checkbox" onchange="toggleCheckbox(this)">
<span class="slider round"></span>
</label>
<script>
function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
if(element.checked){ xhr.open("GET", "/on", true); }
else { xhr.open("GET", "/off", true); }
xhr.send();
}
</script>
</body>
</html>
)==";
// 빌트인 LED가 정의 되지 않은 경우 자신이 사용하는 모듈의
// 내부 LED의 GPIO 번호
int LED_BUILTIN = 2;
// 페이지를 찾을 수 없을 때
void notFound(AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Not found");
}
void setup() {
Serial.begin(115200);
if( !SPIFFS.begin( true ) )
{
Serial.println( F("An Error has occurred while mounting SPIFFS") );
return;
}
pinMode(LED_BUILTIN, OUTPUT);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
// 와이파이가 연결될 때까지 기다린다.
if (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial.printf("WiFi Failed!\n");
return;
}
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// SPIFFS의 CSS파일 연결
server.on( "/my.css", HTTP_GET, [] (AsyncWebServerRequest *request )
{
request->send( SPIFFS, "/my.css", "text/css" );
});
// 루트
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(200, "text/html", index_html);
});
// Receive an HTTP GET request
server.on("/on", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(LED_BUILTIN, HIGH);
request->send(200, "text/plain", "LED ON");
});
// Receive an HTTP GET request
server.on("/off", HTTP_GET, [] (AsyncWebServerRequest *request) {
digitalWrite(LED_BUILTIN, LOW);
request->send(200, "text/plain", "LED OFF");
});
server.onNotFound(notFound);
server.begin(); // 서버 시작
}
void loop() {
}
HTML 파일에서 CSS를 사용한다는 내용입니다.
<link href="my.css" type="text/css" rel="stylesheet" crossorigin="anonymous">
버튼 클릭시 이벤트를 발생시켜 아래의 자바스크립트 코드를 호출합니다.
<script>
function toggleCheckbox(element) {
var xhr = new XMLHttpRequest();
if(element.checked){ xhr.open("GET", "/on", true); }
else { xhr.open("GET", "/off", true); }
xhr.send();
}
</script>
실행 화면
이제는 같은 웹페이지에서 LED를 제어할 수 있습니다.
같은 방법으로 여러개의 스위치를 만들면 더 많은 제어도 가능합니다.
HTML, CSS, JAVASCRIPT를 이용한다면 ESP32 웹서버에 접속하여 많은것을 제어할 수 있습니다.
ip공유기에서 포트포워딩을 설정하여 외부에서도 접속하여 집안의 등을 제어 할 수 있는데,
문제는 ip 주소가 변경되는 문제 입니다. 그래서, 고정ip로 만들어 사용하시면 됩니다.
https://jooduino.tistory.com/8
ESP32 고정 IP 만들기
ESP32 모듈을 공유기에 접속하면 사용하지 않는 ip주소를 받습니다. 하지만, 어떤 주소를 받을지 모르기 때문에 항상 할당받은 ip주소를 확인해야 합니다. 고정 ip를 만들려면 내가 사용하는 공유
jooduino.tistory.com
'ESP32 > 펌웨어' 카테고리의 다른 글
ESP32 OTA를 이용한 펌웨어 업데이트 (2) | 2023.10.03 |
---|---|
ESP32 웹서버 만들기 - 입력 받기 (0) | 2023.10.03 |
아두이노 버튼 라이브러리 (0) | 2023.10.03 |
ESP32 웹서버 만들기 - 버튼 추가 (0) | 2023.09.24 |
ESP32 웹서버 만들기 'Hello world' (0) | 2023.09.20 |