이 튜토리얼은 여러분이 ESP8266을 프로그래밍하여 웹 서버로 만드는 방법을 안내합니다. 이를 통해 웹 인터페이스를 통해 온도 데이터에 접근할 수 있습니다. DS18B20 온도 센서를 부착하여 사용하면, 여러분의 스마트폰이나 PC로 ESP8266이 제공하는 웹 페이지를 방문하여 현재 온도를 쉽게 확인할 수 있습니다. 작동 방식에 대한 간략한 개요는 다음과 같습니다:
ESP8266은 웹 서버로 프로그래밍됩니다.
스마트폰이나 PC의 웹 브라우저에서 ESP8266의 IP 주소를 입력합니다.
ESP8266은 웹 브라우저의 요청에 응답하여 DS18B20 센서에서 읽은 온도가 포함된 웹 페이지를 제공합니다.
우리는 두 가지 예제 코드를 살펴볼 것입니다:
DS18B20 센서에서 측정한 온도를 보여주는 매우 단순한 웹 페이지를 제공하는 ESP8266 코드입니다. 이를 통해 작동 방식을 쉽게 이해할 수 있습니다. HTML 내용이 ESP8266 코드에 포함되어 있습니다.
DS18B20 센서에서 측정한 온도를 보여주는 그래픽 웹 페이지를 제공하는 ESP8266 코드로, HTML 내용이 ESP8266 코드와 분리되어 있습니다.
/* * 이 ESP8266 NodeMCU 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP8266 NodeMCU 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp8266/esp8266-temperature-via-web */#include <ESP8266WiFi.h>#include <ESP8266WebServer.h>#include <OneWire.h>#include <DallasTemperature.h>#define SENSOR_PIN D7 // DS18B20 센서의 DATA 핀에 연결된 ESP8266 핀const char* ssid = "YOUR_WIFI_SSID"; // 변경하세요const char* password = "YOUR_WIFI_PASSWORD"; // 변경하세요OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스 설정DallasTemperature DS18B20(&oneWire); // oneWire를 DallasTemperature 라이브러리에 전달ESP8266WebServer server(80); // 포트 80에서 웹 서버floatgetTemperature() { DS18B20.requestTemperatures(); // 온도를 얻기 위한 명령 보내기float temperature_C = DS18B20.getTempCByIndex(0); // 온도를 °C로 읽기return temperature_C;}voidsetup() {Serial.begin(9600); DS18B20.begin(); // DS18B20 센서 초기화// Wi-Fi에 연결WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(1000);Serial.println("WiFi에 연결 중..."); }Serial.println("WiFi에 연결됨");// ESP8266의 IP 주소 출력Serial.print("ESP8266 웹 서버의 IP 주소: ");Serial.println(WiFi.localIP());// HTML 페이지를 제공하기 위한 경로 정의 server.on("/", HTTP_GET, []() {Serial.println("ESP8266 웹 서버: 새 요청 받음:"); // 디버깅을 위해Serial.println("GET /"); // 디버깅을 위해// 센서에서 온도 얻기float temperature = getTemperature();// 온도를 소수점 두 자리로 포맷String temperatureStr = String(temperature, 2);String html = "<!DOCTYPE HTML>"; html += "<html>"; html += "<head>"; html += "<link rel=\"icon\" href=\"data:,\">"; html += "</head>"; html += "<p>"; html += "Temperature: <span style=\"color: red;\">"; html += temperature; html += "°C</span>"; html += "</p>"; html += "</html>"; server.send(200, "text/html", html); });// 서버 시작 server.begin();}voidloop() {// 클라이언트 요청 처리 server.handleClient();// 여기에 코드 작성}
올바른 ESP8266 보드(예: NodeMCU 1.0 (ESP-12E Module))와 해당 COM 포트를 선택하세요.
Arduino IDE의 왼쪽 바에 있는 Libraries 아이콘을 클릭하세요.
검색 상자에 “Dallas”라고 입력한 다음, Miles Burton의 DallasTemperature 라이브러리를 찾습니다.
DallasTemperature 라이브러리를 설치하려면 Install 버튼을 클릭하세요.
의존성을 설치하라는 요청을 받게 됩니다. OneWire 라이브러리를 설치하려면 Install All 버튼을 클릭하세요.
위의 코드를 복사하고 아두이노 IDE로 열기
코드에서 와이파이 정보(SSID와 비밀번호)를 귀하의 것으로 변경하기
아두이노 IDE에서 Upload 버튼을 클릭하여 코드를 ESP8266에 업로드하기
시리얼 모니터 열기
시리얼 모니터에서 결과 확인하기
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E Module)' on 'COM15')
New Line
9600 baud
Connecting to WiFi...
Connected to WiFi
ESP8266 Web Server's IP address: 192.168.0.5
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2
IP 주소를 찾게 될 것입니다. 이 IP 주소를 스마트폰이나 PC의 웹 브라우저 주소 창에 입력하세요.
시리얼 모니터에서 다음과 같은 출력을 볼 수 있습니다.
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Nodemcu 1.0 (ESP-12E Module)
Newbiely.ino
···
8Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Nodemcu 1.0 (ESP-12E Module)' on 'COM15')
New Line
9600 baud
Connecting to WiFi...
Connected to WiFi
ESP8266 Web Server's IP address: 192.168.0.5
ESP8266 Web Server: New request received:
GET /
Ln 11, Col 1
Nodemcu 1.0 (ESP-12E Module) on COM15
2
아래와 같이 웹 브라우저에서 ESP8266 보드의 매우 간단한 웹 페이지를 볼 수 있습니다:
※ 주의:
위에 제공된 코드를 사용하여 온도 업데이트를 받으려면 웹 브라우저에서 페이지를 새로고침해야 합니다. 다음 파트에서는 웹 페이지를 새로고침하지 않고도 배경에서 온도 값을 업데이트하는 방법을 배우게 될 것입니다.
ESP8266 코드 - 그래픽 웹 페이지
그래픽 웹 페이지에는 다량의 HTML 콘텐츠가 포함되어 있기 때문에, 이전과 같이 ESP8266 코드에 포함시키는 것이 불편해집니다. 이 문제를 해결하기 위해, ESP8266 코드와 HTML 코드를 서로 다른 파일로 분리할 필요가 있습니다:
ESP8266 코드는 .ino 파일에 배치될 것입니다.
HTML 코드(HTML, CSS, Javascript 포함)는 .h 파일에 배치될 것입니다.
HTML 코드를 ESP8266 코드에서 분리하는 방법에 대한 자세한 내용은 ESP8266 - 웹 서버 튜토리얼을 참조하세요.
사용 방법
아두이노 IDE를 열고 새 스케치를 만들어 이름을 지정하세요. 예를 들어, newbiely.kr.ino와 같이요.
아래의 코드를 복사하여 아두이노 IDE로 열어보세요.
/* * 이 ESP8266 NodeMCU 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP8266 NodeMCU 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp8266/esp8266-temperature-via-web */#include <ESP8266WiFi.h>#include <ESP8266WebServer.h>#include"index.h"// index.h 파일 포함#include <OneWire.h>#include <DallasTemperature.h>#define SENSOR_PIN D7 // DS18B20 센서의 DATA 핀에 연결된 ESP8266 핀const char* ssid = "YOUR_WIFI_SSID"; // 변경하세요const char* password = "YOUR_WIFI_PASSWORD"; // 변경하세요OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스 설정DallasTemperature DS18B20(&oneWire); // oneWire를 DallasTemperature 라이브러리에 전달ESP8266WebServer server(80); // 80 포트에서 웹 서버floatgetTemperature() { DS18B20.requestTemperatures(); // 온도를 얻는 명령 보내기float temperature_C = DS18B20.getTempCByIndex(0); // °C 단위로 온도 읽기return temperature_C;}voidsetup() {Serial.begin(9600); DS18B20.begin(); // DS18B20 센서 초기화// Wi-Fi에 연결WiFi.begin(ssid, password);while (WiFi.status() != WL_CONNECTED) {delay(1000);Serial.println("Connecting to WiFi..."); }Serial.println("Connected to WiFi");// ESP8266의 IP 주소 출력 Serial.print("ESP8266 Web Server's IP address: "); Serial.println(WiFi.localIP());// 파일에서 HTML 페이지 제공 server.on("/", HTTP_GET, []() {Serial.println("ESP8266 Web Server: New request received:"); // 디버깅을 위함Serial.println("GET /"); // 디버깅을 위함 server.send(200, "text/html", webpage); // webpage는 index.h 파일에서 옴 });// 온도 데이터를 얻기 위한 경로 정의 server.on("/temperature", HTTP_GET, []() {Serial.println("ESP8266 Web Server: New request received:"); // 디버깅을 위함Serial.println("GET /temperature"); // 디버깅을 위함float temperature = getTemperature();// 온도를 소수점 두 자리로 포맷String temperatureStr = String(temperature, 2); server.send(200, "text/plain", temperatureStr); });// 서버 시작 server.begin();}voidloop() {// 클라이언트 요청 처리 server.handleClient();// 여기에 코드 작성}
코드에서 와이파이 정보(SSID와 비밀번호)를 당신의 것으로 변경하세요.
아두이노 IDE에서 index.h 파일을 다음 방법으로 생성하세요:
시리얼 모니터 아이콘 아래에 있는 버튼을 클릭하고 새 탭을 선택하거나, Ctrl+Shift+N 키를 사용하세요.
파일 이름을 index.h로 지정하고 OK 버튼을 클릭하세요.
아래 코드를 복사하여 index.h에 붙여넣으세요.
/* * 이 ESP8266 NodeMCU 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP8266 NodeMCU 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp8266/esp8266-temperature-via-web */#ifndef WEBPAGE_H#define WEBPAGE_Hconst char* webpage = R"=====(<!DOCTYPE html><html><head><title>ESP8266 - Web Temperature</title><meta name="viewport" content="width=device-width, initial-scale=0.7, maximum-scale=0.7"><meta charset="utf-8"><link rel="icon" href="https://diyables.io/images/page/diyables.svg"><style>body { font-family: "Georgia"; text-align: center; font-size: width/2pt;}h1 { font-weight: bold; font-size: width/2pt;}h2 { font-weight: bold; font-size: width/2pt;}button { font-weight: bold; font-size: width/2pt;}</style><script>var cvs_width = 200, cvs_height = 450;function init() { var canvas = document.getElementById("cvs"); canvas.width = cvs_width; canvas.height = cvs_height + 50; var ctx = canvas.getContext("2d"); ctx.translate(cvs_width/2, cvs_height - 80); fetchTemperature(); setInterval(fetchTemperature, 4000); // Update temperature every 4 seconds}function fetchTemperature() { fetch("/temperature") .then(response => response.text()) .then(data => {update_view(data);});}function update_view(temp) { var canvas = document.getElementById("cvs"); var ctx = canvas.getContext("2d"); var radius = 70; var offset = 5; var width = 45; var height = 330; ctx.clearRect(-cvs_width/2, -cvs_height + 80, cvs_width, cvs_height + 50); ctx.strokeStyle="blue"; ctx.fillStyle="blue";//5-step Degree var x = -width/2; ctx.lineWidth=2;for (var i = 0; i <= 100; i+=5) { var y = -(height - radius)*i/100 - radius - 5; ctx.beginPath(); ctx.lineTo(x, y); ctx.lineTo(x - 20, y); ctx.stroke(); }//20-step Degree ctx.lineWidth=5;for (var i = 0; i <= 100; i+=20) { var y = -(height - radius)*i/100 - radius - 5; ctx.beginPath(); ctx.lineTo(x, y); ctx.lineTo(x - 25, y); ctx.stroke(); ctx.font="20px Georgia"; ctx.textBaseline="middle"; ctx.textAlign="right"; ctx.fillText(i.toString(), x - 35, y); }// shape ctx.lineWidth=16; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.stroke(); ctx.beginPath(); ctx.rect(-width/2, -height, width, height); ctx.stroke(); ctx.beginPath(); ctx.arc(0, -height, width/2, 0, 2 * Math.PI); ctx.stroke(); ctx.fillStyle="#e6e6ff"; ctx.beginPath(); ctx.arc(0, 0, radius, 0, 2 * Math.PI); ctx.fill(); ctx.beginPath(); ctx.rect(-width/2, -height, width, height); ctx.fill(); ctx.beginPath(); ctx.arc(0, -height, width/2, 0, 2 * Math.PI); ctx.fill(); ctx.fillStyle="#ff1a1a"; ctx.beginPath(); ctx.arc(0, 0, radius - offset, 0, 2 * Math.PI); ctx.fill(); temp = Math.round(temp * 100) / 100; var y = (height - radius)*temp/100.0 + radius + 5; ctx.beginPath(); ctx.rect(-width/2 + offset, -y, width - 2*offset, y); ctx.fill(); ctx.fillStyle="red"; ctx.font="bold 34px Georgia"; ctx.textBaseline="middle"; ctx.textAlign="center"; ctx.fillText(temp.toString() + "°C", 0, 100);}window.onload = init;</script></head><body><h1>ESP8266 - Web Temperature</h1><canvas id="cvs"></canvas></body></html>)=====";#endif
이제 코드가 두 개의 파일에 있습니다: newbiely.kr.ino 및 index.h
Arduino IDE에서 Upload 버튼을 클릭하여 코드를 ESP8266에 업로드하십시오.
이전과 같이 PC나 스마트폰의 웹 브라우저를 통해 ESP8266 보드의 웹 페이지에 접속하면 아래와 같이 보입니다:
※ 주의:
index.h에서 HTML 내용을 수정하고 newbiely.kr.ino 파일은 건드리지 않는다면, ESP8266에 코드를 컴파일하고 업로드할 때 Arduino IDE는 HTML 내용을 업데이트하지 않을 것입니다.
이 경우에서 Arduino IDE가 HTML 내용을 업데이트하게 하려면, newbiely.kr.ino 파일에 변경사항을 만들어야 합니다 (예: 빈 줄 추가, 주석 추가...).