아두이노 - 웹을 통한 온도 확인 | Arduino - Temperature via Web

이 튜토리얼에서는 웹을 통해 온도를 제공하는 웹 서버가 되도록 아두이노를 프로그래밍하는 방법을 배워보겠습니다. DS18B20 온도 센서에서 온도를 확인하기 위해 아두이노가 제공하는 웹 페이지에 접속할 수 있습니다. 아래는 그 작동 방식입니다:

Arduino Uno R4 DS18B20 temperature sensor web server

두 개의 예제 코드를 살펴보겠습니다:

준비물

1×Arduino UNO R4 WiFi 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×(Optional) 9V Power Adapter for Arduino Amazon
1×(Recommended) Screw Terminal Block Shield for Arduino Uno 쿠팡 | Amazon
1×(Optional) Transparent Acrylic Enclosure For Arduino Uno 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.

아두이노 우노 R4와 DS18B20 온도 센서에 대하여

아두이노 우노 R4와 DS18B20 온도 센서(핀배열, 작동 방식, 프로그래밍 방법 등)에 대해 잘 모른다면, 다음 튜토리얼에서 그들에 대해 배워보세요:

선연결

Arduino Uno R4 WiFi DS18B20 Temperature Sensor Wiring Diagram

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

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

/* * 이 Arduino 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino/arduino-temperature-via-web */ #include <WiFiS3.h> #include <OneWire.h> #include <DallasTemperature.h> const char ssid[] = "YOUR_WIFI"; // 네트워크 SSID(이름)을 변경하세요 const char pass[] = "YOUR_WIFI_PASSWORD"; // 네트워크 비밀번호를 변경하세요 (WPA용이거나, WEP 키로 사용하세요) const int SENSOR_PIN = 6; // DS18B20 센서의 DQ 핀에 연결된 Arduino 핀 OneWire oneWire(SENSOR_PIN); // OneWire 인스턴스 설정 DallasTemperature tempSensor(&oneWire); // OneWire를 DallasTemperature 라이브러리에 전달 int status = WL_IDLE_STATUS; WiFiServer server(80); float getTemperature() { tempSensor.requestTemperatures(); // 온도를 얻기 위한 명령 전송 float tempCelsius = tempSensor.getTempCByIndex(0); // 섭씨 온도 읽기 return tempCelsius; } void setup() { //시리얼 초기화 및 포트 열릴 때까지 대기: Serial.begin(9600); tempSensor.begin(); // 온도 센서 초기화 String fv = WiFi.firmwareVersion(); if (fv < WIFI_FIRMWARE_LATEST_VERSION) Serial.println("펌웨어를 업그레이드하세요"); // WiFi 네트워크에 연결을 시도함: while (status != WL_CONNECTED) { Serial.print("SSID에 연결을 시도중: "); Serial.println(ssid); // WPA/WPA2 네트워크에 연결. 오픈 네트워크나 WEP 네트워크를 사용하는 경우 이 라인을 변경하세요: status = WiFi.begin(ssid, pass); // 연결을 위해 10초간 대기: delay(10000); } server.begin(); // 이제 연결되었으므로 상태를 출력하세요: printWifiStatus(); } void loop() { // 들어오는 클라이언트를 대기함 WiFiClient client = server.available(); if (client) { // 요청 헤더를 한 줄씩 읽기 while (client.connected()) { if (client.available()) { String HTTP_header = client.readStringUntil('\n'); // HTTP 요청의 헤더 라인 읽기 if (HTTP_header.equals("\r")) // HTTP 요청의 끝 break; Serial.print("<< "); Serial.println(HTTP_header); // 시리얼 모니터에 HTTP 요청 출력 } } // HTTP 응답 전송 // HTTP 응답 헤더 전송 client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // 응답 완료 후 연결이 닫힘 client.println(); // HTTP 헤더와 본문 사이의 구분자 // HTTP 응답 본문 전송 client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<head>"); client.println("<link rel=\"icon\" href=\"data:,\">"); client.println("</head>"); client.println("<p>"); client.print("온도: <span style=\"color: red;\">"); float temperature = getTemperature(); client.print(temperature, 2); client.println("&deg;C</span>"); client.println("</p>"); client.println("</html>"); client.flush(); // 웹 브라우저가 데이터를 수신할 시간을 줌 delay(10); // 연결 닫기: client.stop(); } } void printWifiStatus() { // 보드의 IP 주소 출력: Serial.print("IP 주소: "); Serial.println(WiFi.localIP()); // 수신 신호 강도 출력: Serial.print("신호 강도 (RSSI):"); Serial.print(WiFi.RSSI()); Serial.println(" dBm"); }

사용 방법

  • 아두이노 우노 R4를 처음 사용하는 경우, 아두이노 IDE에서 아두이노 우노 R4 환경 설정하는 방법을 확인하세요.
  • 위의 코드를 복사하여 아두이노 IDE에서 열기
  • 코드에서 와이파이 정보(SSID 및 비밀번호)를 귀하의 것으로 변경하세요
  • 아두이노 IDE에서 Upload 버튼을 클릭하여 코드를 아두이노에 업로드
  • 시리얼 모니터 열기
  • 시리얼 모니터에서 결과 확인하기
COM6
Send
Attempting to connect to SSID: YOUR_WIFI IP Address: 192.168.0.2 signal strength (RSSI):-39 dBm
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  
  • IP 주소를 찾게 됩니다. 이 IP 주소를 스마트폰 또는 PC의 웹 브라우저 주소 창에 입력하세요.
  • Serial Monitor에서 다음과 같은 출력을 볼 수 있습니다.
COM6
Send
Attempting to connect to SSID: YOUR_WIFI IP Address: 192.168.0.2 signal strength (RSSI):-41 dBm New HTTP Request << GET / HTTP/1.1 << Host: 192.168.0.2 << Connection: keep-alive << Cache-Control: max-age=0 << Upgrade-Insecure-Requests: 1 << User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) << Accept: text/html,application/xhtml+xml,application/xml << Accept-Encoding: gzip, deflate << Accept-Language: en-US,en;q=0.9
Autoscroll Show timestamp
Clear output
9600 baud  
Newline  

아래와 같이 웹 브라우저에서 아주 간단한 아두이노 보드 웹 페이지를 보게 될 것입니다:

Arduino Uno R4 temperature web browser

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

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

  • 아두이노 코드는 .ino 파일에 배치될 것입니다.
  • HTML 코드(HTML, CSS, Javascript 포함)는 .h 파일에 배치될 것입니다.

사용 방법

  • 아두이노 IDE를 열고 새 스케치를 만들고, 이름을 입력하세요. 예를 들어, ArduinoGetStarted.com.ino라고 하면 됩니다.
  • 아래 코드를 복사하고 아두이노 IDE로 엽니다.
/* * 이 Arduino 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino/arduino-temperature-via-web */ #include <WiFiS3.h> #include "index.h" #include <OneWire.h> #include <DallasTemperature.h> const char ssid[] = "YOUR_WIFI"; // 네트워크 SSID(이름)를 변경하세요 const char pass[] = "YOUR_WIFI_PASSWORD"; // 네트워크 비밀번호를 변경하세요 (WPA용이거나 WEP의 키로 사용하세요) const int SENSOR_PIN = 6; // DS18B20 센서의 DQ 핀에 연결된 아두이노 핀 OneWire oneWire(SENSOR_PIN); // oneWire 인스턴스를 설정 DallasTemperature tempSensor(&oneWire); // oneWire를 DallasTemperature 라이브러리에 전달 int status = WL_IDLE_STATUS; WiFiServer server(80); float getTemperature() { tempSensor.requestTemperatures(); // 온도를 얻기 위한 명령어 보내기 float tempCelsius = tempSensor.getTempCByIndex(0); // 섭씨 온도 읽기 return tempCelsius; } void setup() { //직렬 통신을 초기화하고 포트가 열릴 때까지 기다림: Serial.begin(9600); tempSensor.begin(); // 온도 센서를 초기화 String fv = WiFi.firmwareVersion(); if (fv < WIFI_FIRMWARE_LATEST_VERSION) Serial.println("Please upgrade the firmware"); // WiFi 네트워크에 연결을 시도: while (status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // WPA/WPA2 네트워크에 연결. 오픈 또는 WEP 네트워크를 사용하는 경우 이 줄을 변경하세요: status = WiFi.begin(ssid, pass); // 연결을 위해 10초간 대기: delay(10000); } server.begin(); // 이제 연결되었으므로 상태를 출력하세요: printWifiStatus(); } void loop() { // 들어오는 클라이언트를 대기 WiFiClient client = server.available(); if (client) { // HTTP 요청 헤더를 한 줄씩 읽기 while (client.connected()) { if (client.available()) { String HTTP_header = client.readStringUntil('\n'); // HTTP 요청의 헤더 라인 읽기 if (HTTP_header.equals("\r")) // HTTP 요청의 끝 break; Serial.print("<< "); Serial.println(HTTP_header); // HTTP 요청을 시리얼 모니터에 출력 } } // HTTP 응답 보내기 // HTTP 응답 헤더를 보냅니다 client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); // 응답 완료 후 연결이 종료됩니다 client.println(); // HTTP 헤더와 본문 사이의 구분자 // HTTP 응답 본문을 보냅니다 float temp = getTemperature(); String html = String(HTML_CONTENT); html.replace("TEMPERATURE_MARKER", String(temp, 2)); // 마커를 실제 값으로 교체 client.println(html); client.flush(); // 웹 브라우저가 데이터를 받는 시간을 제공 delay(10); // 연결을 종료합니다: client.stop(); } } void printWifiStatus() { // 보드의 IP 주소를 출력합니다: Serial.print("IP Address: "); Serial.println(WiFi.localIP()); // 받은 신호 강도를 출력합니다: Serial.print("signal strength (RSSI):"); Serial.print(WiFi.RSSI()); Serial.println(" dBm"); }
  • 코드 내의 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에 붙여넣으세요.

    /* * 이 Arduino 코드는 newbiely.kr 에서 개발되었습니다 * 이 Arduino 코드는 어떠한 제한 없이 공개 사용을 위해 제공됩니다. * 상세한 지침 및 연결도에 대해서는 다음을 방문하세요: * https://newbiely.kr/tutorials/arduino/arduino-temperature-via-web */ const char *HTML_CONTENT = R""""( <!DOCTYPE html> <html> <head> <title>Arduino - 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); update_view(TEMPERATURE_MARKER); } 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, -350, cvs_width, cvs_height); 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 - Web Temperature</h1> <canvas id="cvs"></canvas> </body> </html> )"""";
    • 이제 두 개의 파일에 코드를 가지고 있습니다: ArduinoGetStarted.com.inoindex.h
    • 아두이노 IDE에서 Upload 버튼을 클릭하여 아두이노에 코드를 업로드하세요
    • 이전과 같이 웹 브라우저를 통해 아두이노 보드의 웹 페이지에 접속하면 아래와 같이 보여집니다:
    Arduino temperature web browser

    ※ NOTE THAT:

    index.h 파일 내의 HTML 콘텐츠를 변경하되 ArduinoGetStarted.com.ino 파일을 수정하지 않으면 아두이노 IDE는 ESP32에 코드를 컴파일하고 업로드 할 때 HTML 콘텐츠를 새로 고치거나 업데이트하지 않습니다.

    이 상황에서 아두이노 IDE가 HTML 콘텐츠를 업데이트하도록 하려면 ArduinoGetStarted.com.ino 파일에서 수정을 해야 합니다. 예를 들어, 빈 줄을 추가하거나 주석을 삽입할 수 있습니다. 이 작업은 IDE가 프로젝트에 변경사항이 있음을 인식하게 하여 업데이트된 HTML 콘텐츠가 업로드에 포함되도록 보장합니다.

※ 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!