This tutorial guides the construction of a beginner-friendly temperature and humidity monitor using Raspberry Pi Pico WH, a DHT11 sensor, and other components. The device measures the indoor environment's temperature and humidity and by using WiFi, sends this data to the Adafruit IO platform for visualization and monitoring. MicroPython is used to program the Raspberry Pi Pico, and the data is transmitted to Adafruit IO following MQTT protocol.
Depending on the developer’s experience with the hardware and software components, this fairly straightforward project should take around 1-2 hours to complete.
## **Objective**
As a student with no previous knowledge of IoT, this course has been an opportunity to learn and gain experience with different hardwares and softwares. I chose this specific project to utilize all materials from the Electrokit essential start-kit for the course and also gain an understanding of IoT as a complete beginner through building a simple yet interesting project. The purpose of this project is to create an accessible and affordable indoor temperature and humidity monitoring system, especially in the current hot, humid and unpredictable summer weather.
The device gives insight into indoor temperature and humidity and notifies when the temperature is too high. Similarly, the project can help gain insights into the environmental conditions of a specific location and the data can be used for weather monitoring in homes, offices, greenhouses, etc.
## **Materials**
The following materials have been used to build the project:
| Image | Item | Specification |
| -------- | -------- | -------- |
|| **Raspberry Pi Pico WH** | Microcontroller |
|| **DHT11** | Digital Temperature and Humidity Sensor |
|| 400 Connection Deck | Breadboard |
|| Male A-Micro B 1.8m | USB Cable |
|| 4x Male-Male Cable 30cm | Jumper Wires |
|| LED Red 5mm | LED Light |
|| Carbon Film Resistor (330R) | Resistor |
I purchased the start-kit from Electrokit for all the essential hardware for the course which costs 399kr and contains the required materials for this project and some extra items.
## **Computer Setup**
I used Virtual Studio Code and Pymakr plug-in to configure my computer (Windows OS) and followed the tutorials on the Applied IoT Roadmap for the project. Take the following steps to replicate the setup:
1. Download and install [Node js](https://nodejs.org/en).
2. Download and install [VS Code](https://code.visualstudio.com/Download).
3. Install Pymakr from the Extensions Manager in VS Code.
4. Download the [MicroPython firmware](https://micropython.org/download/rp2-pico-w/) (uf2) for Raspberry Pi Pico W.
5. Flash the Raspberry Pi Pico WH with the downloaded UF2 bootloader by connecting the micro-USB end of the cable to the Raspberry Pi Pico WH, and while holding the BOOTSEL key on the board, connect the USB Type A of the cable to the computer. Next, copy-paste the downloaded uf2 file in the new drive named “RPI-RP2” opened in the computer file system. At this point, the Raspberry Pi Pico WH is automatically reset and ready for use.
6. Create a MicroPython project in VS code.
Once the computer is set up, the next step is to move on to the hardware and start building the physical part of the indoor temperature and humidity monitor.
## **Putting Everything Together**
At this stage of the project, it is time to attach the DHT11 sensor to the board along with the other materials.
Here is the Raspberry Pi Pico W pinout (same as Raspberry Pi Pico WH):

The DHT11 sensor can be connected to the Raspberry Pi Pico WH the following way,
| DHT11 | Raspberry Pi Pico WH |
| ------- | -------------------- |
| VCC (+) | 3.3V |
| OUT (0) | GP27 |
| GND (-) | GND |
Connect a red LED light to the GP15 along with an appropriate resistor and place all the components on the breadboard as per the circuit diagram.
*Note: A regular 5mm LED light ideally requires a 200Ω resistor. I used a 330Ω resistor as it was the closest to 200Ω of the available resistors in the Electokit package.*
**Circuit Diagram**

## **Platform**
It is possible to implement self-hosted IoT solutions to successfully visualize the data from the temperature and humidity monitor. However, for a beginner these solutions are more complex compared to the other options. There are other big data IoT solutions available such as Google Cloud IoT, Amazon IoT, etc. which are not necessary for a simple project like this one. Hence, the choice of platform for this project was a low-code IoT solution, **Adafruit**. It is fairly easy to implement, offers great visuals, and is free of charge. So, it is perfectly efficient for any beginner’s project.
## **The Code**
The main code for the project is divided into three files. Emulate the code in each file to replicate the project.
1. Create a `mqtt.py` file in the project workspace in VS code since the MQTT protocol is used to send data to the Adafruit platform. Copy-paste the content from the [MQTT library](https://github.com/iot-lnu/applied-iot/blob/master/Pycom%20Micropython%20(esp32)/network-examples/mqtt_ubidots/mqtt.py) into the file.
2. To transmit data, ensure Wi-Fi connectivity. Create an extra file as `secrets.py` to hide the original Wi-Fi credential.
```javascript
secrets = {
'ssid' : 'WIFI Name', # your wifi credential
'password' : 'WIFI Password',
}
```
Add the following code to `boot.py` to establish the Wi-Fi connection when the device boots:
```javascript
def connect_to_wifi():
import machine
import network
import time
from secrets import secrets
wlan = network.WLAN(network.STA_IF) # put modem on station mode
if not wlan.isconnected(): # check if already connected
print('Connecting to network...')
wlan.active(True) # activate network interface
wlan.config(pm = 0xa11140)
wlan.connect(secrets["ssid"], secrets["password"])
print('Waiting for connection...', end='')
# check if it is connected otherwise wait
while not wlan.isconnected() and wlan.status() >= 0:
print('.', end='')
time.sleep(1)
ip = wlan.ifconfig()[0]
print('\nConnected on {}'.format(ip)) # print the ip assigned by router
return ip
def http_get(url = 'http://detectportal.firefox.com/'):
import socket # used by html get request
import time # used for delay
_, _, host, path = url.split('/', 3) # separate url request
addr = socket.getaddrinfo(host, 80)[0][-1] # get ip address of host
s = socket.socket() # initialise the socket
s.connect(addr) # try connecting to host address
# send http request to the host with specific path
s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
time.sleep(1)
rec_bytes = s.recv(10000)
print(rec_bytes)
s.close()
try:
ip = connect_to_wifi()
except KeyboardInterrupt:
print("Keyboard interrupt")
try:
http_get()
except Exception as err:
print("Exception", err)
```
3. For the main project functionality, I add the following code to `main.py` to monitor the temperature and humidity from the sensor and to get visual notification when the temperature is higher than 25°C:
```javascript
import machine
import dht
import time
import ubinascii # for binary to text conversions
import ujson # for json encoding and decoding
from mqtt import MQTTClient
tempSensor = dht.DHT11(machine.Pin(27))
led = machine.Pin(15, machine.Pin.OUT)
AIO_SERVER = "io.adafruit.com" # adafruit io mqtt server address
AIO_PORT = 1883 # adafruit io mqtt server port
AIO_USER = "Meem_Hoque" # adafruit io username
AIO_KEY = "aio_vjji14Az31W7mIMLGjMAI7hqyRxs" # adafruit io API key
AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # generate a unique client id based on the device id
AIO_TEMPERATURE_FEED = "Meem_Hoque/feeds/temperature" # adafruit io feed for temperature
AIO_HUMIDITY_FEED = "Meem_Hoque/feeds/humidity" # adafruit io feed for humidity
client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY)
# create an mqtt client instance
def connect_mqtt():
client.connect() # connect to the mqtt server
def publish_mqtt(topic, value):
payload = ujson.dumps({'value': value}) # convert the value to json format
client.publish(topic, payload) # publish the payload to the specified mqtt topic
connect_mqtt() # connect to the mqtt server
while True:
try:
tempSensor.measure()
temperature = tempSensor.temperature()
humidity = tempSensor.humidity()
if temperature > 25:
led.on()
print("Start the fan") # note for future project
else:
led.off()
publish_mqtt(AIO_TEMPERATURE_FEED, temperature)
publish_mqtt(AIO_HUMIDITY_FEED, humidity)
print("Temperature: {} degrees Celsius".format(temperature))
print("Humidity: {}%".format(humidity))
except:
print("Error reading data from sensor")
time.sleep(15)
```
## **Transmitting the Data**
The sensor data is sent to Adafruit IO every 15 seconds through **Wi-Fi**, which is the wireless protocol and the transport protocol is **MQTT**. **Webhook** message to own discord server is also used to get message notifications when the temperature is above 25°C. In this project, only the indoor temperature and humidity are being measured and the device does not need to be active constantly unless the intention is to record the data. I chose Wi-Fi as it is very simple to set up. From a power consumption perspective, there are more environment-friendly options such as LoRa or Sigfox as using a Wi-Fi connection requires a fair amount of energy.
## **Presenting the Data**
Adafruit offers 5 feeds with 30 entries per minute limitation for a free account. In this specific project, the device is sending data to the platform every 15 seconds, it does not face any issue with saving the data on the database for free. This again justifies the reason for choosing Adafruit IO for a straightforward IoT project. I have two feeds for the project, Temperature, and Humidity. The dashboard shows the present temperature and humidity read by the sensor as well as the changes over time through line charts. The green indicator on the dashboard turns red and Adafruit triggers Webhook messages to my discord server when the temperature exceeds 25°C.
Final look of the dashboard:

## **Finalizing the Design**
Here is the final design of the completed device. It is fairly simple and the LED light turns on when it is too hot in the room (>25°C).

Considering it was my first IoT project, the project went very well and I am proud of the results. I am surprised that I was able to learn the basics of IoT hardware and software components in such a short amount of time. I want to continue learning and build more advanced projects over time. This course taught me the basics of how to program microcontrollers, use sensors and other IoT devices as well as present the data online. I plan on improving this project and re-build it in such a way that if the indoor temperature is higher than 25°C, the fan is automatically turned on. Moreover, I plan on using different network connection methods like LoRaWAN.