ESP8266 - 웹을 통한 온도 확인 | ESP8266 - Temperature via Web

이 튜토리얼은 여러분이 ESP8266을 프로그래밍하여 웹 서버로 만드는 방법을 안내합니다. 이를 통해 웹 인터페이스를 통해 온도 데이터에 접근할 수 있습니다. DS18B20 온도 센서를 부착하여 사용하면, 여러분의 스마트폰이나 PC로 ESP8266이 제공하는 웹 페이지를 방문하여 현재 온도를 쉽게 확인할 수 있습니다. 작동 방식에 대한 간략한 개요는 다음과 같습니다:

ESP8266 NodeMCU DS18B20 temperature sensor web server

우리는 두 가지 예제 코드를 살펴볼 것입니다:

준비물

1×ESP8266 NodeMCU Amazon
1×Micro USB Cable Amazon
1×DS18B20 Temperature Sensor (WITH Adapter) 쿠팡 | Amazon
1×DS18B20 Temperature Sensor (WITHOUT Adapter) Amazon
1×Jumper Wires Amazon
1×(Optional) ESP8266 Screw Terminal Adapter Amazon
공개: 이 섹션에서 제공된 링크 중 일부는 제휴 링크입니다. 이 링크를 통해 구매한 경우 추가 비용없이 수수료를 받을 수 있습니다. 지원해 주셔서 감사합니다.

Buy Note: Many DS18B20 sensors available in the market are unreliable. We strongly recommend buying the sensor from the DIYables brand using the link provided above. We tested it, and it worked reliably.

ESP8266 웹 서버 및 DS18B20 온도 센서에 대하여

ESP8266 웹 서버와 DS18B20 온도 센서(핀 배치, 작동 원리, 프로그래밍 방법 등)에 대해 잘 모른다면, 다음 튜토리얼에서 배워보세요:

선연결

ESP8266 NodeMCU Web Server DS18B20 Temperature Sensor Wiring Diagram

이 이미지는 Fritzing을 사용하여 만들어졌습니다. 이미지를 확대하려면 클릭하세요.

ESP8266의 핀 배치ESP8266 및 다른 구성 요소에 전원을 공급하는 방법에 대해 더 많이 보십시오.

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에서 웹 서버 float getTemperature() { DS18B20.requestTemperatures(); // 온도를 얻기 위한 명령 보내기 float temperature_C = DS18B20.getTempCByIndex(0); // 온도를 °C로 읽기 return temperature_C; } void setup() { 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 += "&deg;C</span>"; html += "</p>"; html += "</html>"; server.send(200, "text/html", html); }); // 서버 시작 server.begin(); } void loop() { // 클라이언트 요청 처리 server.handleClient(); // 여기에 코드 작성 }

사용 방법

아두이노 IDE에서 ESP8266을 시작하는 방법은 다음과 같습니다:

  • ESP8266을 처음 사용하는 경우, Arduino IDE에서 ESP8266 환경 설정하는 방법 튜토리얼을 참조하세요.
  • 다이어그램에 표시된 대로 구성 요소를 연결하세요.
  • USB 케이블을 사용하여 ESP8266 보드를 컴퓨터에 연결하세요.
  • 컴퓨터에서 Arduino IDE를 엽니다.
  • 올바른 ESP8266 보드(예: NodeMCU 1.0 (ESP-12E Module))와 해당 COM 포트를 선택하세요.
  • Arduino IDE의 왼쪽 바에 있는 Libraries 아이콘을 클릭하세요.
  • 검색 상자에 “Dallas”라고 입력한 다음, Miles Burton의 DallasTemperature 라이브러리를 찾습니다.
  • DallasTemperature 라이브러리를 설치하려면 Install 버튼을 클릭하세요.
ESP8266 NodeMCU Dallas Temperature library

의존성을 설치하라는 요청을 받게 됩니다. OneWire 라이브러리를 설치하려면 Install All 버튼을 클릭하세요.

ESP8266 NodeMCU onewire library
  • 위의 코드를 복사하고 아두이노 IDE로 열기
  • 코드에서 와이파이 정보(SSID와 비밀번호)를 귀하의 것으로 변경하기
  • 아두이노 IDE에서 Upload 버튼을 클릭하여 코드를 ESP8266에 업로드하기
  • 시리얼 모니터 열기
  • 시리얼 모니터에서 결과 확인하기
COM6
Send
Connecting to WiFi... Connected to WiFi ESP8266 Web Server's IP address: 192.168.0.5
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • IP 주소를 찾게 될 것입니다. 이 IP 주소를 스마트폰이나 PC의 웹 브라우저 주소 창에 입력하세요.
  • 시리얼 모니터에서 다음과 같은 출력을 볼 수 있습니다.
COM6
Send
Connecting to WiFi... Connected to WiFi ESP8266 Web Server's IP address: 192.168.0.5 ESP8266 Web Server: New request received: GET /
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

아래와 같이 웹 브라우저에서 ESP8266 보드의 매우 간단한 웹 페이지를 볼 수 있습니다:

ESP8266 NodeMCU temperature web server

※ NOTE THAT:

위에 제공된 코드를 사용하여 온도 업데이트를 받으려면 웹 브라우저에서 페이지를 새로고침해야 합니다. 다음 파트에서는 웹 페이지를 새로고침하지 않고도 배경에서 온도 값을 업데이트하는 방법을 배우게 될 것입니다.

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 포트에서 웹 서버 float getTemperature() { DS18B20.requestTemperatures(); // 온도를 얻는 명령 보내기 float temperature_C = DS18B20.getTempCByIndex(0); // °C 단위로 온도 읽기 return temperature_C; } void setup() { 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(); } void loop() { // 클라이언트 요청 처리 server.handleClient(); // 여기에 코드 작성 }

코드에서 와이파이 정보(SSID와 비밀번호)를 당신의 것으로 변경하세요.

아두이노 IDE에서 index.h 파일을 다음 방법으로 생성하세요:

  • 시리얼 모니터 아이콘 아래에 있는 버튼을 클릭하고 새 탭을 선택하거나, Ctrl+Shift+N 키를 사용하세요.
Arduino IDE 2 adds file

파일 이름을 index.h로 지정하고 OK 버튼을 클릭하세요.

Arduino IDE 2 adds file index.h

아래 코드를 복사하여 index.h에 붙여넣으세요.

/* * 이 ESP8266 NodeMCU 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP8266 NodeMCU 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp8266/esp8266-temperature-via-web */ #ifndef WEBPAGE_H #define WEBPAGE_H const 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.inoindex.h

Arduino IDE에서 Upload 버튼을 클릭하여 코드를 ESP8266에 업로드하십시오.

이전과 같이 PC나 스마트폰의 웹 브라우저를 통해 ESP8266 보드의 웹 페이지에 접속하면 아래와 같이 보입니다:

ESP8266 NodeMCU temperature web browser server

※ NOTE THAT:

  • index.h에서 HTML 내용을 수정하고 newbiely.kr.ino 파일은 건드리지 않는다면, ESP8266에 코드를 컴파일하고 업로드할 때 Arduino IDE는 HTML 내용을 업데이트하지 않을 것입니다.
  • 이 경우에서 Arduino IDE가 HTML 내용을 업데이트하게 하려면, newbiely.kr.ino 파일에 변경사항을 만들어야 합니다 (예: 빈 줄 추가, 주석 추가...).

※ OUR MESSAGES

  • Please feel free to share the link of this tutorial. However, Please do not use our content on any other websites. We invested a lot of effort and time to create the content, please respect our work!