아두이노 나노 ESP32 - 웹을 통한 온도 | Arduino Nano ESP32 - Temperature via Web

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

Arduino Nano ESP32 DS18B20 temperature sensor web server

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

준비물

1×Arduino Nano ESP32 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) Screw Terminal Adapter for Arduino Nano 쿠팡 | 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 온도 센서(핀 아웃, 작동 원리, 프로그래밍 방법 등)에 대해 잘 모른다면, 다음 튜토리얼에서 배워보세요:

선연결

Arduino Nano ESP32 Web Server DS18B20 Temperature Sensor Wiring Diagram

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

아두이노 나노 ESP32 코드 - 간단한 웹 페이지

/* * 이 Arduino Nano ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino Nano ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino-nano-esp32/arduino-nano-esp32-temperature-via-web */ #include <WiFi.h> #include <ESPAsyncWebServer.h> #include <OneWire.h> #include <DallasTemperature.h> #define SENSOR_PIN D2 // Arduino Nano ESP32 핀을 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 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"); // ESP32의 IP 주소 출력 Serial.print("Arduino Nano ESP32 웹 서버의 IP 주소: "); Serial.println(WiFi.localIP()); // HTML 페이지를 제공하는 경로 정의 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("Arduino Nano 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() { // 여기에 코드 작성 }

사용 방법

Arduino Nano ESP32를 시작하는 방법은 다음과 같습니다:

아두이노 나노 ESP32에 처음이라면, 아두이노 IDE에서 아두이노 나노 ESP32 환경을 설정하는 방법에 대한 튜토리얼을 참조하세요. 아두이노 나노 ESP32 소프트웨어 설치.

제공된 다이어그램에 따라 구성 요소를 연결하세요.

USB 케이블을 사용하여 아두이노 나노 ESP32 보드를 컴퓨터에 연결하세요.

컴퓨터에서 아두이노 IDE를 실행하세요.

Arduino Nano ESP32 보드와 해당 COM 포트를 선택하세요.

아두이노 IDE의 왼쪽 탐색 바에 있는 Library Manager 아이콘을 클릭하여 라이브러리 관리자를 엽니다.

“ESPAsyncWebServer”를 검색하고, ESPAsyncWebServer를 찾습니다.

Install 버튼을 클릭하여 lacamera의 ESPAsyncWebServer 라이브러리를 설치하세요.

Arduino Nano ESP32 ESPAsyncWebServer library

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

Arduino Nano ESP32 ESPAsyncWebServer dependencies library

검색 상자에서 “DallasTemperature”을 검색한 다음, Miles Burton의 DallasTemperature 라이브러리를 찾으세요.

DallasTemperature 라이브러리를 설치하려면 Install 버튼을 클릭하세요.

Arduino Nano ESP32 Dallas Temperature library

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

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

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

Arduino Nano ESP32 temperature web server

※ NOTE THAT:

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

아두이노 나노 ESP32 코드 - 그래픽 웹 페이지

그래픽 웹 페이지는 대량의 HTML 콘텐츠를 포함하고 있으므로, 이전과 같이 아두이노 나노 ESP32 코드에 포함시키기가 불편해집니다. 이 문제를 해결하기 위해, 아두이노 나노 ESP32 코드와 HTML 코드를 다른 파일로 분리할 필요가 있습니다:

  • 아두이노 나노 ESP32 코드는 .ino 파일에 배치될 것입니다.
  • HTML 코드(HTML, CSS, 및 자바스크립트 포함)는 .h 파일에 배치될 것입니다.

HTML 코드를 Arduino Nano ESP32 코드에서 분리하는 방법에 대한 자세한 내용은 Arduino Nano ESP32 - 웹 서버 튜토리얼을 참조해 주세요.

사용 방법

  • Arduino IDE를 열고 새 스케치를 생성하십시오. 이름을 지정하십시오. 예를 들어, newbiely.kr.ino와 같이 이름을 지정할 수 있습니다.
  • 아래 코드를 복사하여 Arduino IDE에서 열어보십시오.
/* * 이 Arduino Nano ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino Nano ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino-nano-esp32/arduino-nano-esp32-temperature-via-web */ #include <WiFi.h> #include <ESPAsyncWebServer.h> #include <OneWire.h> #include <DallasTemperature.h> #include "index.h" // index.h 파일을 포함합니다. #define SENSOR_PIN D2 // Arduino Nano ESP32의 DS18B20 센서의 데이터 핀에 연결된 핀 const char* ssid = "YOUR_WIFI_SSID"; // 변경하세요 const char* password = "YOUR_WIFI_PASSWORD"; // 변경하세요 OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스를 설정합니다. DallasTemperature DS18B20(&oneWire); // DallasTemperature 라이브러리에 oneWire를 전달합니다. AsyncWebServer server(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에 연결됨"); // ESP32의 IP 주소를 출력 Serial.print("Arduino Nano ESP32 웹 서버의 IP 주소: "); Serial.println(WiFi.localIP()); // 파일에서 HTML 페이지를 제공 server.on("/", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("Arduino Nano ESP32 웹 서버: 새 요청이 접수되었습니다."); // 디버깅을 위함 Serial.println("GET /"); // 디버깅을 위함 request->send(200, "text/html", webpage); // webpage는 index.h 파일에서 가져옴 }); // 온도 데이터를 얻기 위한 경로를 정의 server.on("/temperature", HTTP_GET, [](AsyncWebServerRequest* request) { Serial.println("Arduino Nano ESP32 웹 서버: 새 요청이 접수되었습니다."); // 디버깅을 위함 Serial.println("GET /temperature"); // 디버깅을 위함 float temperature = getTemperature(); // 소수점 둘째 자리로 온도를 포맷 String temperatureStr = String(temperature, 2); request->send(200, "text/plain", temperatureStr); }); // 서버 시작 server.begin(); } void loop() { // 여기에 코드를 작성하세요 }

코드에서 WiFi 정보(SSID 및 비밀번호)를 귀하의 것으로 변경하십시오.

Arduino IDE에서 index.h 파일을 만들려면:

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

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

Arduino IDE 2 adds file index.h

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

/* * 이 Arduino Nano ESP32 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino Nano ESP32 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino-nano-esp32/arduino-nano-esp32-temperature-via-web */ #ifndef WEBPAGE_H #define WEBPAGE_H const char* webpage = R"=====( <!DOCTYPE html> <html> <head> <title>Arduino Nano 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>Arduino Nano ESP32 - Web Temperature</h1> <canvas id="cvs"></canvas> </body> </html> )====="; #endif
  • 이제 코드가 두 파일에 있습니다: newbiely.kr.inoindex.h
  • Arduino IDE에서 Upload 버튼을 클릭하여 코드를 Arduino Nano ESP32에 업로드하세요.
  • PC나 스마트폰의 웹 브라우저를 통해 이전과 같이 Arduino Nano ESP32 보드의 웹 페이지에 접속하세요. 아래와 같이 보일 것입니다:
Arduino Nano 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!