---
# System prepended metadata

title: Monitor Indoor Temperature and Humidity

---

# Monitor Indoor Temperature and Humidity
Hayden Ross (hr222nn)

This report provides the basic guidelines of setting up a generic Esp32 microcontroller to monitor temperature and humidity in ones home or business.

Dependent on experience this project could be completed in about 2-3 hours.




## Objective
This project's aim is to practically ensure that the correct temperature and humidity levels, in ones home, are present in areas such as basements, storage units, or attics. By monitoring these levels this can help reduce any chance of mold or bacterial growth which thrive in these warm, damp areas.  This project also proves promising for businesses such as zoos, plant stores, and cigar stores. Zoos need to confirm that their animals, which live in tropical climates, are receiving the right levels of humidity and temperature so they can survive. This method also pertains to certain plants which are being sold at plant stores. Cigar store owners or smokers need to have the correct humidity to prevent their cigars from going stale. Although it is a simple design, it has many beneficial uses in different areas; that is the reason why I have chosen this as my project.


## Material

- Esp32: Programmable microcontroller.
- Expansion Board: Allows for better connectivity of microcontroller on breadboard.
-  Breadboard: Builds temporary circuits.
-  Jumper wire: Connects 2 points of a circuit. 
-  LCD screen: Shows results of the code printed on the screen.
-  DHT11: Sensor for measuring temperature and humidity.
-  9V battery adapter: Provides power to Esp32 board.
-  Micro-USB cable: Allows data to be sent to Esp32 board.

The following table presents where I purchased the required material, along with extra parts, needed to design this project.

| Material | Description | Price    | Where to Buy  | Image   |
|:-------- |:--------:   |:--------:| :--------:| --------:
| Freenove Super Starter Kit for ESP32-WROVER     |  This starter kit contains an Esp32 microcontroller, expansion board, breadboard, resistors, jumper wires, LCD screen, lights, basic sensors, buttons, camera, micro-USB cable, and 9V battery adapter        |  359 kr |   [amazon.se](https://www.amazon.se/Freenove-ESP32-WROVER-Contained-Compatible-Bluetooth/dp/B09BC5B4H6/ref=asc_df_B09BC5B4H6/?tag=shpngadsglesm-21&linkCode=df0&hvadid=476567314728&hvpos=&hvnetw=g&hvrand=3532496763897829262&hvpone=&hvptwo=&hvqmt=&hvdev=m&hvdvcmdl=&hvlocint=&hvlocphy=1012372&hvtargid=pla-1546526821427&psc=1)        | ![](https://i.imgur.com/oEBkcHo.jpg)        |
|  Temperature & Humidity Sensor for Arduino      |   DHT11 sensor which measures temperature and humidity      |   99.90 kr | [kjell.com](https://www.kjell.com/se/produkter/el-verktyg/arduino/moduler/temperatur-och-luftfuktighetssensor-for-arduino-p87086)      |    ![](https://i.imgur.com/uHrX0jD.jpg)
     

## Computer Setup
### Install Atom
The IDE I chose to use for this project was **Atom**. Atom is a free open-source text and code editor which was developed by GitHub. Its developers quote it as, "The hackable editor of the 21st Century." To install Atom simply click [here](https://atom.io/) and you will be directed to their installation page. Simply choose and download the correct version which pertains to your computers operating system.



### Install Node.js
**Node.js** must first be installed to be able to use the Pymakr plug-in. To install Node.js click [here](https://nodejs.org/en/) and choose the Long-Term Support (LTS) version. Simply follow the instructions to properly install Node.js.

### Install Pymakr Plug-in
After both Atom and Node.js has been properly installed you are now able to install the Pymakr plug-in.
1. Open Atom
2. Click `File >> Settings >> Install`
3. Type pymakr in the search bar & click install
![](https://i.imgur.com/42EZeTV.jpg)


### Flashing the Firmware
This section goes into detail on how to flash a generic Esp32 on a Windows OS device.

**Follow these steps to flash your device**
1. Connect Esp32 board to your computer with a USB cable.
2. Download the VCP drivers [**here**](https://www.silabs.com/documents/public/software/CP210x_Windows_Drivers.zip). Dependent on your Windows version either open the file ending with **_x64** or **_x86**.
3. Download the MicroPython firmware bin file [**here**](https://micropython.org/resources/firmware/esp32-20220117-v1.18.bin).
4. Click this [link](https://nabucasa.github.io/esp-web-flasher/) to be directed the the Esp32 web flasher tool.
5. Choose 460800 Baud, Press Connect, Select your serial port your device is connected to, Press Connect
![](https://i.imgur.com/zfEjVqq.jpg)

6. Once connected, Press Erase
![](https://i.imgur.com/06mrlMP.jpg)

7. Click Ok, and wait a few minutes until everything is erased
![](https://i.imgur.com/mGp0eJB.jpg)


8. Change the Offset to 1000, and Choose the Micropython Firmware bin file from earlier. Then Press Program
![](https://i.imgur.com/ffo7aBM.jpg)

Now your device has been successfully flashed with the Micropython firmware. 

## Putting Everything Together
The image below is a representaion of how I have set up my project. The only differences of my actual project and this diagram is that I used my expansion board to attach my Esp32 microcontroller to the breadboard. I have color coded the wires for easier readability. The **Red** wires indicate power, the **Black** wires indicate ground, the **Yellow** wires indicate data, and the **Blue** wire indicates the clock. I initially setup the DHT11 sensor first by grounding it, and supplying power to it of 3.3V. I then connected the sensor data pin of the DHT11 to Pin 14 of my Esp32 microcontroller. After the sensor was attached I started connecting the LCD screen. I first started by grounding the LCD screen and supplied power of 5V because it requires more voltage to operate. The Serial Data line (SDA), which transmits all the data, was connected with Pin 21 of the Esp32 board. The Serial Clock line (SCL), which synchronizes time between devices, was coupled with Pin 22.

This design is only for development setup; mainly due to the fact that nothing has been soldered. The wires can be easily removed from the bredboard causing it to not function properly. Another big factor why it is not ready for production is that everything is exposed to environmental risks, because there is no protective housing. Wires are prone to being severed and the unit as a whole is at risk for water damage. 

![](https://i.imgur.com/rHi0Pnd.png)

## Platform 
For this project I decided to use **Datacake** via WiFi to send all my sensoring data to. Datacake is a low-code, cloud based platform to design applications for IoT devices in a user-friendly way. There are a few different plans Datacake offers to its users, but I decided to go with the free basic plan. This plan allows a user to be able to connect up to 2 devices at once and stores data for up to 1 week. If this product were to be placed on a larger scale then consideration of a different plan is highly recommended. Datacake uses an MQTT broker to output data from devices in a secure fashion. The below image illustrates how the broker sends and receives data to devices by using a subscription based method called Topics.

![](https://i.imgur.com/L3G4haC.jpg)(Photo by [Bivocom](https://www.bivocom.com/blog/how-to-set-up-mqtt))


## The Code

All code for this project can be found [here](https://github.com/HR055/Temperature-Humidity).

Copy and paste all code in the provided GitHub repository. I have removed the credentials of my WiFi for security reasons, so in the `config.py` file one can enter their own credentials accordingly. The Datacake credentials will also need to be changed compliant with their own Datacake account; this can be found under the configuration tab on the dashboard. 


### `boot.py`
This code connects the Esp32 board with my WiFi by inserting my WiFi's name in the SSID variable and its password in the PASS variable of the `do_connect()` function. Esp32s do not support any connection higher than 2.4 GHz, so be certain that your WiFi is compatable before connection.
```python=
from config import SSID, PASS

def do_connect():
    import network
    sta_if = network.WLAN(network.STA_IF)       # Put modem on Station mode
    if not sta_if.isconnected():                # Check if already connected
        print('connecting to network...')
        sta_if.active(True)                     # Activate network interface
        sta_if.connect(SSID, PASS)     # Your WiFi Credential
        # Check if it is connected otherwise wait
        while not sta_if.isconnected():
            pass
    # Print the IP assigned by router
    print('network config:', sta_if.ifconfig())

# WiFi Connection
do_connect()
```




### `main.py`
The `main.py` file uses a number of imported libraries to receive functionality over the sensor and LCD screen. The `mqtt.py` was provided by the teaching assistants of this course and the `lcd_api.py` and `i2c_lcd.py` original sourcing by Dave Hyland can be found [here](https://github.com/dhylands/python_lcd/tree/master/lcd). By connecting to Datacake's MQTT broker the Esp32 board is able to send the sensor data to Datacake. 
```python=
from mqtt import MQTTClient
import time
import ujson
import machine
from machine import Pin, SoftI2C
from time import sleep
from dht import DHT11
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
from config import SERIAL_NUMBER, MQTT_BROKER, TOKEN

# Setup
sensor = DHT11(Pin(14))
I2C_ADDR = 0x27
totalRows = 2
totalColumns = 16
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=10000)
lcd = I2cLcd(i2c, I2C_ADDR, totalRows, totalColumns)

def sub_cb(topic, msg):
   print(msg)

# MQTT Setup
client = MQTTClient(SERIAL_NUMBER,
                    MQTT_BROKER,
                    user=TOKEN,
                    password=TOKEN,
                    port=1883)

client.set_callback(sub_cb)
client.connect()
print('connected')

# topics for datacake
my_topic = 'dtck-pub/project-1/fed60c70-6232-4997-969a-3f3589be09e4/TEMPERATURE'
my_topic2 = 'dtck-pub/project-1/fed60c70-6232-4997-969a-3f3589be09e4/HUMIDITY'

payload = 0
payload2 = 0


while True:
    lcd.clear() # clears lcd screen
    sensor.measure()    # receives sensor data
    temp = sensor.temperature() # temperature data
    humidity = sensor.humidity()    # humidity data

    # prints on LCD
    print(lcd.putstr('Temp: %2.0f C' %temp + '\n'))
    print(lcd.putstr('Humidity: %2.0f%%' %humidity))


    # publishes data to datacake
    payload = temp
    payload2 = humidity
    client.publish(topic=my_topic, msg=str(payload))
    client.publish(topic=my_topic2, msg=str(payload2))


    client.check_msg()
    time.sleep(120)
```


## Transmitting the Data / Connectivity
As previously stated my Esp32 microcontroller has been programmed to connect to my WiFi of 2.4 GHz and uses an MQTT broker provided by Datacake to transmit data to other devices. The below code represents that the Esp32 device will sleep for a duration of 2 minutes before measuring another reading. The sleeping time can be adjusted to personal preferencing. The more time the device is sleeping the more you save on the battery's life.

```python=
time.sleep(120)
```
## Presenting the Data
Datacake is user-friendly in being able to setup a new dashboards of different widgets for many project.

I have set up the dashboard so that a user is able to see both the current temperature and humidity levels. I have also created 2 different graphs to monitor these levels over a weekly basis. The timeframe of these graphs can be adjusted dependant on how you would like to analyze the data. Datacake saves newly measured data immediately into their database. Since I have the free plan my data is only accumulated for a week and then removed from their database. With a better plan one can look at yearly data results and determine when are the crucial time periods an area needs to be dehumidified. Analyzing this data can also determine when someone should start thinking about turning on or off their cooling/heating systems for a more sustainable environment. 
![](https://i.imgur.com/sfKeJTh.jpg)

## Finalizing the Design
This project was very interesting and makes you appreciate all the simple technology that we use on a daily basis. I wish I had more time to invest into creating a more complicated design, but with the shortage of Heltec devices I fell a little behind waiting for parts. Setting up this project was a rather smooth process with all the parts involved.
![](https://i.imgur.com/FcnipxX.jpg)
