오늘은 아두이노로 웹서버에 가변저항 값을 표시하는 프로그램을 만들어보겠습니다.
아두이노 WIFI ESP8266 D1R1 보드를 사용했구요,
회로 구성은 아래와 같습니다.
자세한 예제 내용)
1) 가변저항 값 위에 일시(날짜 및 시간)도 함께 표시되어야 한다.
2) 웹 브라우저 창 크기에 상관없이 가변저항 값이 가운데 정렬 되어야 한다.
// 퀴즈 : 웹 서버에 가변저항 값 표시하기 with whole html code
// 값 표시 요건 : 가변저항 값 위에 일시(날짜 및 시간)도 함께 표시되어야 한다.
// 스타일시트 작성 요건 : 웹 브라우저 창 크기에 상관없이 가변저항 값이 가운데 정렬 되어야 한다.
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h> // 웹서버 관련 기능 제공
#define POT_PIN A0
// wifi id, pw
const char *ssid = "yangminseok";
const char *password = "04160416";
ESP8266WebServer server(80);
// html 전체 코드를 한번에 저장한다! raw
String html = R"(
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Yang's page</title>
<style>
*{
color: black;
.centered { display: table; margin-left: auto; margin-right: auto; }
}
</style>
// 가운데 정렬
<style>
html{
width: 100%;
height: 100%;
}
body{
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div>
<h1></h1>
<h2>가변저항 : <span>%d</span></h2>
</div>
<script>
document.querySelector("h1").textContent = new Date(); // 현재시간 표시
</script>
</body>
</html>
)";
int cnt = 0;
// html 문서 안에 조도센서 값을 삽입하는 함수
void handlePage(){
String html_copy = html;
int potValue = analogRead(POT_PIN);;
String potValue_s = String(potValue);
Serial.println(potValue_s);
html_copy.replace("%d", potValue_s);
server.send(200, "text/html", html_copy); // 정상응답, html형식, 내용
}
void setup() {
Serial.begin(9600);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("Use this URL : ");
Serial.println(WiFi.localIP());
server.on("/", handlePage); // 키워드에 따른 함수 매핑
server.begin();
}
void loop() {
server.handleClient(); // 웹서버 동작 ing...
}
코드 실행 이후 시리얼모니터에 출력된 URL(IP)를 웹브라우저에 입력하면 됩니다.