
NodeMCU V2에서 DS18B20 온도센서로부터 값읽어 웹페이지에 보여주기NodeMCU V22023. 10. 11. 21:58
Table of Contents
반응형
NodeMCU V2에서 DS18B20 온도 센서로부터 값을 읽어 웹페이지에 보여주는 예제입니다.
2016. 6. 13 최초작성
2022. 9. 12 업데이트
관련 포스트
Arduino IDE에서 NodeMCU V2를 사용하기
https://webnautes.tistory.com/1925
1. Arduino IDE의 메뉴에서 스케치 > 라이브러리 포함하기 > 라이브러리 관리를 선택합니다
2. onewire를 검색하여 설치합니다.
3. dallas temperature를 검색하여 설치합니다..
4. 아래처럼 NodeMCU V2와 DS18B20 온도 센서를 연결합니다.
- DS18B20 온도 센서의 평평한 부분을 봤을때 왼쪽부터 핀 번호가 1, 2, 3 입니다.
- DS18B20 온도 센서의 2번 핀과 3번 핀을 4.7K 저항을 연결해줘야 합니다.
- GND, 3.3V, D1이 NodeMCU V2에 연결되어야 하는 핀 이름입니다.
5. 아래 코드를 복사하여 Arduino IDE에 붙여넣고 업로드 버튼을 클릭합니다.
코드에서 SSID와 패스워드는 사용중인 공유기에 맞추어 변경해야 합니다.
const char* ssid = "ssid";
const char* pass = "password";
#include <ESP8266WiFi.h> #include <ESP8266WebServer.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS D1 WiFiServer server(80); OneWire oneWire(ONE_WIRE_BUS); DallasTemperature DS18B20(&oneWire); const char* ssid = "ssid"; const char* pass = "password"; char temperatureString[6]; void setup(void){ Serial.begin(115200); Serial.println(""); WiFi.begin(ssid, pass); while (WiFi.status() != WL_CONNECTED) { delay(100); Serial.print("."); } Serial.print("\n"); // Start the server server.begin(); // Print the IP address Serial.print("Use this URL to connect: "); Serial.print("http://"); Serial.print(WiFi.localIP()); Serial.println("/"); DS18B20.begin(); } float getTemperature() { float temp; do { DS18B20.requestTemperatures(); temp = DS18B20.getTempCByIndex(0); delay(100); } while (temp == 85.0 || temp == (-127.0)); return temp; } void loop() { float temperature = getTemperature(); dtostrf(temperature, 2, 2, temperatureString); // send temperature to the serial console Serial.println(temperatureString); WiFiClient client = server.available(); if (!client) { return; } // Wait until the client sends some data Serial.println("new client"); while(!client.available()){ delay(1); } // Read the first line of the request String request = client.readStringUntil('\r'); Serial.println(request); client.flush(); // Return the response client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println(""); // do not forget this one client.println("<!DOCTYPE HTML>"); client.println("<html>"); client.println("<meta http-equiv=\"refresh\" content=\"1\"> "); client.println("<h1>"); client.println(temperatureString); client.println("</h1>"); client.println("</html>"); } |
6. 메뉴에서 툴 > 시리얼 모니터를 선택합니다.
7. 보드레이트를 115200으로 변경하면 온도가 출력되는 것을 볼 수 있습니다.
8. NodeMCU V2를 PC에 연결한 선을 뺐다가 다시 연결해줍니다.
. 이 출력되다가 공유기에 연결되면 접속할 수 있는 IP를 출력해주고 나서 온도를 계속 출력합니다.
공유기 접속에 문제 있는 경우 핸드폰의 핫스팟을 사용해보세요.
............................................................................................................................... Use this URL to connect: http://172.20.10.8/ 27.19 27.19 |
9. 확인한 IP를 웹브라우저에서 접속하면 1초마다 웹페이지가 갱신되면서 온도가 출력되는 것을 볼 수 있습니다.
반응형
'NodeMCU V2' 카테고리의 다른 글
Arduino IDE에서 NodeMCU V2를 사용하기 (0) | 2023.10.11 |
---|