ESP32 - 웹을 통한 온도 | ESP32 - Temperature via Web

이 가이드에서는 ESP32를 웹 서버로 기능하도록 프로그래밍하는 과정을 탐색할 것입니다. 이를 통해 웹 인터페이스를 통해 온도 데이터에 접근할 수 있습니다. 부착된 DS18B20 온도 센서를 사용하여 스마트폰이나 PC로 ESP32가 제공하는 웹 페이지를 방문함으로써 현재 온도를 쉽게 확인할 수 있습니다. 작동 방식에 대한 간략한 개요는 다음과 같습니다:

ESP32 DS18B20 temperature sensor web server

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

준비물

1×ESP-WROOM-32 Dev Module 쿠팡 | Amazon
1×USB Cable Type-C 쿠팡 | Amazon
1×DS18B20 Temperature Sensor (WITH Adapter) 쿠팡 | Amazon
1×DS18B20 Temperature Sensor (WITHOUT Adapter) Amazon
1×Jumper Wires Amazon
1×(Recommended) ESP32 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.

ESP32 웹 서버와 DS18B20 온도 센서에 대하여

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

선연결

ESP32 Web Server DS18B20 Temperature Sensor Wiring Diagram

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

ESP32 및 다른 구성 요소에 전원을 공급하는 방법에 대해 잘 알지 못하는 경우, 다음 튜토리얼에서 안내를 찾을 수 있습니다: ESP32 전원 공급 방법.

ESP32 코드 - 간단한 웹 페이지

/* * 이 ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp32/esp32-temperature-via-web */ #include <WiFi.h> #include <ESPAsyncWebServer.h> #include <OneWire.h> #include <DallasTemperature.h> #define SENSOR_PIN 17 // ESP32 핀 GPIO17이 DS18B20 센서의 DATA 핀에 연결됨 const char* ssid = "YOUR_WIFI_SSID"; // 변경하세요 const char* password = "YOUR_WIFI_PASSWORD"; // 변경하세요 OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스 설정 DallasTemperature DS18B20(&oneWire); // oneWire를 DallasTemperature 라이브러리에 전달 AsyncWebServer server(80); float getTemperature() { DS18B20.requestTemperatures(); // 온도를 얻기 위한 명령 보내기 float tempC = DS18B20.getTempCByIndex(0); // °C 단위로 온도 읽기 return tempC; } 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"); // ESP32의 IP 주소 출력 Serial.print("ESP32 Web Server's IP address: "); Serial.println(WiFi.localIP()); // HTML 페이지를 제공하기 위한 경로 정의 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("ESP32 웹 서버: 새 요청 수신됨:"); // 디버깅을 위함 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>"; request->send(200, "text/html", html); }); // 서버 시작 server.begin(); } void loop() { // 여기에 코드를 작성하세요 }

사용 방법

  • ESP32를 처음 사용한다면, Arduino IDE에서 ESP32 개발 환경 설정하는 방법을 참고하세요.
  • 위 이미지와 같이 배선하세요.
  • ESP32 보드를 마이크로 USB 케이블을 이용해 PC에 연결하세요.
  • PC에서 Arduino IDE를 엽니다.
  • 올바른 ESP32 보드(예: ESP32 Dev Module)와 COM 포트를 선택하세요.
  • Arduino IDE의 왼쪽 네비게이션 바에서 Library Manager 아이콘을 클릭해 라이브러리 관리자를 엽니다.
  • “ESPAsyncWebServer”를 검색하고, lacamera가 만든 ESPAsyncWebServer를 찾으세요.
  • Install 버튼을 클릭해 ESPAsyncWebServer 라이브러리를 설치하세요.
ESP32 ESPAsyncWebServer library

종속성을 설치하라는 요청을 받게 됩니다. Install All 버튼을 클릭하세요.

ESP32 ESPAsyncWebServer dependencies library
  • 검색 창에서 “DallasTemperature”을 검색한 다음, Miles Burton의 DallasTemperature 라이브러리를 찾아보세요.
  • DallasTemperature 라이브러리를 설치하려면 Install 버튼을 클릭하세요.
ESP32 Dallas Temperature library

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

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

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

ESP32 temperature web server

※ NOTE THAT:

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

ESP32 코드 - 그래픽 웹 페이지

그래픽 웹 페이지에는 많은 양의 HTML 콘텐츠가 포함되어 있으므로 이전과 같이 ESP32 코드에 내장하는 것이 불편해집니다. 이 문제를 해결하기 위해, ESP32 코드와 HTML 코드를 다른 파일로 분리할 필요가 있습니다:

  • ESP32 코드는 .ino 파일에 위치할 것입니다.
  • HTML 코드(HTML, CSS, 및 Javascript를 포함)는 .h 파일에 위치할 것입니다.

HTML 코드를 ESP32 코드에서 분리하는 방법에 대한 자세한 내용은 ESP32 - 웹 서버 튜토리얼을 참조하십시오.

사용 방법

  • Arduino IDE를 열고 새 스케치를 생성하고 이름을 지정하십시오. 예를 들어, newbiely.kr.ino
  • 아래 코드를 복사하여 Arduino IDE로 열십시오.
/* * 이 ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp32/esp32-temperature-via-web */ #include <WiFi.h> #include <ESPAsyncWebServer.h> #include "index.h" // index.h 파일 포함 #include <OneWire.h> #include <DallasTemperature.h> #define SENSOR_PIN 17 // ESP32의 GPIO17 핀이 DS18B20 센서의 DATA 핀에 연결됨 const char* ssid = "YOUR_WIFI_SSID"; // 변경하세요 const char* password = "YOUR_WIFI_PASSWORD"; // 변경하세요 OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스 설정 DallasTemperature DS18B20(&oneWire); // oneWire를 DallasTemperature 라이브러리에 전달 AsyncWebServer server(80); float getTemperature() { DS18B20.requestTemperatures(); // 온도를 얻기 위한 명령어 전송 float tempC = DS18B20.getTempCByIndex(0); // 온도를 °C로 읽기 return tempC; } 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"); // ESP32의 IP 주소 출력 Serial.print("ESP32 Web Server's IP address: "); Serial.println(WiFi.localIP()); // 파일에서 HTML 페이지 제공 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("ESP32 Web Server: New request received:"); // 디버깅용 Serial.println("GET /"); // 디버깅용 request->send(200, "text/html", webpage); // webpage는 index.h 파일에서 }); // 온도 데이터를 얻기 위한 경로 정의 server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("ESP32 Web Server: New request received:"); // 디버깅용 Serial.println("GET /temperature"); // 디버깅용 float temperature = getTemperature(); // 온도를 소수점 두 자리까지 형식화 String temperatureStr = String(temperature, 2); request->send(200, "text/plain", temperatureStr); }); // 서버 시작 server.begin(); } void loop() { // 여러분의 코드 여기에 }
  • 코드에서 WiFi 정보 (SSID 및 비밀번호)를 귀하의 것으로 변경하세요.
  • 아두이노 IDE에서 index.h 파일을 생성하는 방법:
    • 직렬 모니터 아이콘 아래 버튼을 클릭한 다음 새 탭을 선택하거나 Ctrl+Shift+N 키를 사용하세요.
    Arduino IDE 2 adds file

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

    Arduino IDE 2 adds file index.h

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

    /* * 이 ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/esp32/esp32-temperature-via-web */ #ifndef WEBPAGE_H #define WEBPAGE_H const char* webpage = R"=====( <!DOCTYPE html> <html> <head> <title>ESP32 - 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>ESP32 - Web Temperature</h1> <canvas id="cvs"></canvas> </body> </html> )====="; #endif

    이제 두 개의 파일에 코드를 가지고 있습니다: newbiely.kr.inoindex.h

    Arduino IDE에서 Upload 버튼을 클릭하여 ESP32에 코드를 업로드하세요.

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

    ESP32 temperature web browser server

    ※ NOTE THAT:

    • index.h의 HTML 내용을 수정하고 newbiely.kr.ino 파일을 건드리지 않는 경우, 코드를 ESP32에 컴파일하고 업로드할 때 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!