I recently built a simple temperature sensor using a NodeMCU (ESP8266) and a DHT22. This reads the temperature and humidity roughly every 30 seconds and pushes the data to a MQTT server so I can handle the data elsewhere.
The NodeMCU wakes up every 30 seconds and connects to my local WiFi network. Once connected it takes a sensor reading and publishes it to my MQTT server. It then delays for a few seconds to ensure the message is sent, then goes into deep sleep.
The deep sleep is a function I wasn’t aware of on the ESP8266 before. It just a case of wiring up D0 to RST and calling ESP.deepsleep() in the code. When the device wakes up, it’s like its been turned on for the first time.
The code and wiring is available on my GitHub https://github.com/robertprice/NodeMCU_MQTT_Temperature.
Reading the data from MQTT
As the purpose of the sensor was to just send the data to a MQTT server in a simple format, I needed to write something to listen to the published messages the device was sending.
I was able to do this using a simple NodeRED program to listen to incoming MQTT messages, and send them to debug console, and to a CSV file for later processing.
I added a timestamp and built the CSV line using a mustache template. This is then appended to a CSV file I put in my /tmp directory.
The data looks like this
2020-05-07T13:09:17.635Z,29.70 2020-05-07T13:09:54.586Z,29.80 2020-05-07T13:10:31.508Z,29.80 2020-05-07T13:11:06.936Z,29.80 2020-05-07T13:11:42.409Z,29.80
Using the CSV data
To test the data is being logged correctly, I wrote a simple R script parse the data and plot a diagram from it. As the CSV had no header columns, I had to rename the first column names as read_csv used the first line values by default.
library(tidyverse)
library(readr)
library(ggplot2)
temperatures <- read_csv("temperatures.csv", col_types = cols(`2020-05-07T13:09:17.635Z` = col_datetime()))
temperatures <- rename(temperatures, c("2020-05-07T13:09:17.635Z"="datetime", "29.70"="temperature"))
shedtemperatures <- temperatures %>% select(datetime, temperature) %>% filter(datetime >= as.Date("2020-05-09") & datetime < as.Date("2020-05-10"))
ggplot(data=shedtemperatures, aes(x=datetime, y=temperature, group=1)) geom_line() + ggtitle("Temperature in the Dev Shed")
This gave me the following plot…
The maximum temperature in the shed I placed the sensor in was 33.1C.