---
# System prepended metadata

title: Sauna Temperature and Humidity Monitoring Using IoT
tags: ['IoT ', RGB SMD LED, DHT11 and DHT22, VScode, adafruit, Wi-Fi]

---

_This project is written by Natalia Timokhova (nt222in)_

[toc]

### Project description:
This tutorial aims to guide beginners in building an IoT device for monitoring temperature and humidity levels within a sauna using DHT11 and DHT22 sensors. The device utilizes an RGB SMD LED, a whiteboard, wires, a Raspberry Pi Pico (Pico W), and the Adafruit platform as the dashboard for data visualization. The tutorial will cover the following steps:

1. Hardware Setup:
    - Selecting and connecting the DHT11 and DHT22 sensors to the Raspberry Pi Pico (Pico W).
    - Configuring the RGB SMD LED for indicating measurement levels.
    - Organizing the components on a whiteboard for a neat and functional setup.

2. Software Development:
    - Writing code in Pymakr (Visual Studio Code) to read the sensors.

3. IoT Connectivity:
    - Establishing an internet connection for data transmission.
    - Configuring the Raspberry Pi Pico (Pico W) to connect to a Wi-Fi network.
    - Utilizing appropriate protocols (e.g., MQTT) to send data to the Adafruit platform.

4. Dashboard Integration:
    - Creating a dashboard on the Adafruit platform to visualize and analyze the collected data.
    - Configuring the dashboard to receive and display real-time temperature and humidity measurements.
    - Implementing alerts or notifications on the dashboard based on measurement thresholds.

**Estimated time to build:** 4-5 hours from start to completion.

### Objective:
I chose to build this specific device as a beginner to experience the entire data acquisition and processing chain in an IoT system. The purpose of the device is to monitor temperature and humidity levels in a sauna, ensuring optimal comfort and health benefits. 

Saunas often require specific temperature and humidity conditions for optimal comfort and health benefits. By monitoring these parameters, we can ensure that the sauna environment remains within the desired range.

By analyzing the data, we can gain insights into sauna conditions, identify patterns, and optimize temperature and humidity control. This project serves as a foundation for learning IoT basics and can provide valuable knowledge for future IoT applications.


### Material:
To build the IoT device for monitoring temperature and humidity in the sauna, the following materials are needed:
1. Raspberry Pi Pico WH: This microcontroller board serves as the main controller for the IoT device. It provides the necessary processing power and connectivity capabilities.
2. USB Cable A-Male to Micro B-Male: This cable is used to connect the Raspberry Pi Pico to a computer or power source for programming and power supply.
3. Jumper Wires (30cm Male-to-Male): These wires are used to establish connections between components on the breadboard or whiteboard.
4. Digital Temperature and Humidity Sensor (DHT11 and DHT22): This sensor measures both temperature and humidity levels in the sauna environment.
5. LED Module RGB SMD: This module is used as the indicator to display measurement levels, with red indicating higher levels and green indicating lower levels.

**Here are the details of where the materials can be purchased:**

[Start Kit – Applied IoT at Linnaeus University (2023):](https://www.electrokit.com/produkt/start-kit-applied-iot-at-linnaeus-university-2023/)
Price: 399.00 SEK
Includes (among the others): 1x Raspberry Pi Pico WH, 1x USB Cable A-Male to Micro B-Male (1.8m), 20x Jumper Wires (30cm Male-to-Male), 1x DHT11 and DHT22 Digital Temperature and Humidity Sensor

[Sensor Kit – 25 Moduler:](https://www.electrokit.com/produkt/sensor-kit-25-moduler/)
Price: 299.00 SEK
Includes (among other sensors): LED Module RGB SMD

### Computer setup
**To set up your computer for programming the IoT device, follow these steps:**

1. Install the chosen IDE: Download and install Visual Studio Code (VS Code) from the official website.

2. Install the Pymakr plugin: Open VS Code and go to the Extensions manager. Search for "Pymakr" and click "Install" to add the plugin.

3. Install Node.js: Download and install Node.js from the official website. Node.js is required for the Pymakr plugin.

4. Verify the installation: Open the terminal and run the "which node" command to ensure Node.js is installed correctly.

5. Confirm successful installation: Open VS Code and check if the Pymakr plugin is installed. Look for the Pymakr icon in the left menu. If the installation was successful, you see the "Projects" and "DEVICE" sections.

6. With the computer set up, you can proceed to flash the firmware and upload your code to the IoT device using the provided IDE (VS Code) and the Pymakr plugin.

**To update the firmware on your Raspberry Pi Pico W and run a test code, follow these steps:**

1. Remove the ESD sponge from the Raspberry Pi Pico board.

2. Download the latest MicroPython firmware from the official website.

3. Connect the Raspberry Pi Pico to your computer using a USB cable.

4. Hold down the BOOTSEL key on the board and connect the USB cable to your computer.

5. Copy the downloaded firmware [.uf2 file](https://micropython.org/download/rp2-pico-w/) to the "RPI-RP2" drive that appears.

6. Wait for the board to automatically disconnect and reconnect.

**To test the board:**

1. Make sure you have installed an IDE (such as VSCode or Thonny).

2. Enter the provided code snippet in the IDE.

3. Verify that the board responds with the expected output.

### Putting everything together

To connect all the electronics, including the RGB SMD LED module, the DHT11 and DHT22 temperature and humidity sensor, the whiteboard, and the Raspberry Pi Pico W, follow these steps:

![](https://hackmd.io/_uploads/rkdzCe7Y2.png)


RGB SMD LED Module:
- The RGB SMD LED module has four pins: one for the red color, one for the green color, one for the blue color, and one for the common cathode (GND).
- Connect the red pin of the LED module to a GPIO pin on the Raspberry Pi Pico W.
- Connect the green pin of the LED module to a different GPIO pin on the Raspberry Pi Pico W.
- Connect the blue pin of the LED module to another GPIO pin on the Raspberry Pi Pico W.
- Connect the common cathode pin (GND) of the LED module to the GND pin on the Raspberry Pi Pico W.

DHT11 and DHT22 Temperature and Humidity Sensor:
- The sensor has three pins: VCC (power), GND (ground), and DATA (measurement pin).
- Connect the VCC pin of the sensor to a 3.3V pin on the Raspberry Pi Pico W.
- Connect the GND pin of the sensor to the GND pin on the Raspberry Pi Pico W.
- Connect the DATA pin of the sensor to any available GPIO pin on the Raspberry Pi Pico W. Take note of the chosen GPIO pin for later use in the code.


:::info
:information_source: In the picture below it could be seen that LoRaWAN was connected as well, but it was not included in the final project because the coverage disappeared in the place of the sensor connection.
:::


![](https://hackmd.io/_uploads/HJyFxWXK2.png)

### Platform

Platform Choice:
The chosen platform for this project is **Adafruit**. It is a beginner-friendly IoT platform that offers cloud-based services and tools for building and managing IoT projects.

Local Installation or Cloud:
Adafruit is a cloud-based platform, accessible through a web browser, providing cloud services for storing and processing IoT data.

Paid Subscription or Free:
Adafruit offers both free and paid subscription plans, allowing users to choose based on their project requirements and scale.

Scaling the Idea:
Users can upgrade their subscription plan and leverage Adafruit's integration with other cloud platforms and services to scale the project.

Functionality:
Adafruit provides functionality such as data storage, visualization, device management, and integration with other services. It offers APIs and libraries for various hardware platforms and a web interface for the configuration and monitoring of IoT devices.


### The code

Load the libraries

```python=126
import time                   # Allows use of time.sleep() for delays
from mqtt import MQTTClient   # For use of MQTT protocol to talk to Adafruit IO
import ubinascii              # Conversions between binary data and various encodings
import machine                # Interfaces with hardware components
import micropython            # Needed to run any MicroPython code
import random                 # Random number generator
from machine import Pin       # Define pin
import dht
```

Initial settings, where we determine in which port of the microprocessor it is necessary to connect the temperature and humidity sensor, and in which ports we connect the color sensors (3 legs out of 4):

```python=137
tempSensor = dht.DHT11(machine.Pin(27)) # code is working for DHT11 and DHT22

LED_Pin_Red = Pin(26, Pin.OUT)
LED_Pin_Green = Pin(28, Pin.OUT)
LED_Pin_Blue = Pin(22, Pin.OUT)
```

Settings for Wi-fi and Adafruit:
```python=144
# Wireless network
WIFI_SSID = "***************"
WIFI_PASS = "***************"

# Adafruit IO (AIO) configuration
AIO_SERVER = "io.adafruit.com"
AIO_PORT = 1883
AIO_USER = "nataliata"
AIO_KEY = "*********************"
AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id())  # Can be anything
AIO_HUMIDITY_FEED = "nataliata/feeds/humidity"
AIO_TEMPERATURE_FEED = "nataliata/feeds/temperature"
AIO_CONTROL_FEED = "nataliata/feeds/control"
```


Function to connect Pico to the WiFi:

```python=164
def do_connect():
    import network
    from time import sleep
    import machine
    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
        # set power mode to get WiFi power-saving off (if needed)
        wlan.config(pm = 0xa11140)
        wlan.connect(WIFI_SSID, WIFI_PASS)  # Your WiFi Credential
        print('Waiting for connection...', end='')
        # Check if it is connected otherwise wait
        while not wlan.isconnected() and wlan.status() >= 0:
            print('.', end='')
            sleep(1)
    # Print the IP assigned by router
    ip = wlan.ifconfig()[0]
    print('\nConnected on {}'.format(ip))
    return ip 
```

Callback Function to respond to messages from Adafruit IO:

```python=190
def sub_cb(topic, msg):          # sub_cb means "callback subroutine"
    print((topic, msg))          # Outputs the message that was received. Debugging use.
    if msg == b"ON":             # If message says "ON" ...
        pass                 # ... then LED on
    elif msg == b"OFF":          # If message says "OFF" ...
        pass               # ... then LED off
    else:                        # If any other message is received ...
        print("Unknown message") # ... do nothing but output that it happened.

# Function to generate a random number between 0 and the upper_bound
def random_integer(upper_bound):
    return random.getrandbits(32) % upper_bound
```

Try a WiFi Connection and use the MQTT protocol to connect to Adafruit IO:

```python=226
try:
    ip = do_connect()
except KeyboardInterrupt:
    print("Keyboard interrupt")

# Use the MQTT protocol to connect to Adafruit IO
client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY)

# Subscribed messages will be delivered to this callback
client.set_callback(sub_cb)
client.connect()
client.subscribe(AIO_TEMPERATURE_FEED)
client.subscribe(AIO_HUMIDITY_FEED)
client.subscribe(AIO_CONTROL_FEED)
print("Connected to %s, subscribed to %s, %s topic" % (AIO_SERVER, AIO_HUMIDITY_FEED,AIO_TEMPERATURE_FEED ))
```

For the operation of the sensors we define the temperature threshold, which will switch the color of the sensor from green to red. In this case, we use 28 because the project is being tested at room temperature, but in a sauna, it could be 60 or 70 degrees. The measurements take place every 10 seconds until an error occurs or until we stop the measurements ourselves. And if we interrupt the measurements, then all the LED lamps go out (value(0)) to save energy and in order the sustainability of the project.

```python=244
try:                      # Code between try: and finally: may cause an error
                          # so ensure the client disconnects the server if
                          # that happens.
    while 1:              # Repeat this loop forever
        client.check_msg()# Action a message if one is received. Non-blocking.
        #send_random()     # Send a random number to Adafruit IO if it's time.
        try:
            client.publish(topic=AIO_CONTROL_FEED, msg = "1")
            tempSensor.measure()
            temperature = tempSensor.temperature()
            humidity = tempSensor.humidity()
            client.publish(topic=AIO_TEMPERATURE_FEED, msg=str(temperature))
            client.publish(topic=AIO_HUMIDITY_FEED, msg=str(humidity))
            print("Temperature is {} degrees Celsius and Humidity is {}%".format(temperature, humidity))
            if int(temperature) > 28:
                LED_Pin_Red.value(1)
                LED_Pin_Green.value(0)
                LED_Pin_Blue.value(0)
            else:
                LED_Pin_Green.value(1)
                LED_Pin_Red.value(0)
                LED_Pin_Blue.value(0)
            time.sleep(10)

        except KeyboardInterrupt:
            client.publish(topic=AIO_CONTROL_FEED, msg = "0")
            time.sleep(1)
            LED_Pin_Green.value(0)
            LED_Pin_Red.value(0)
            LED_Pin_Blue.value(0)
            raise
        
        except Exception as error:
            print("Exception occurred", error)

finally:                  # If an exception is thrown ...
    client.disconnect()   # ... disconnect the client and clean up.
    client = None
    print("Disconnected from Adafruit IO.")
```


### Transmitting the Data/Connectivity

This project transmits the data to the internet using Wi-Fi connectivity and the MQTT protocol. MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol commonly used in IoT applications for efficient and reliable data transmission.

Steps for Data Transmission:

1. Data Sending Frequency:
The data is sent every 10 seconds from the IoT device to the Adafruit platform.

2. Wireless Protocol:
The chosen wireless protocol for connectivity is Wi-Fi. The IoT device connects to a Wi-Fi network to establish internet connectivity.

3. Transport Protocol:
The transport protocol used for data transmission is MQTT. MQTT provides a publish-subscribe architecture, where the IoT device publishes data on specific topics, and subscribers can receive and process the published data.

4. Code and Protocol Selection:
The code running on the IoT device is responsible for capturing sensor data and publishing it using MQTT. The choice of MQTT is based on its lightweight nature, efficient data transfer, and support for IoT deployments.

The code implementation involves:

- Establishing a Wi-Fi connection on the IoT device to connect to the local network.
- Using MQTT libraries or APIs to establish a connection with the Adafruit MQTT broker.
- Defining a topic for publishing the sensor data.
- Configuring the code to send data every 10 seconds.
- Implementing a condition to check the temperature value and control the LED color (red if temperature > 28, green otherwise).
- If the code execution is stopped, the LED is turned off to indicate the interruption.

![](https://hackmd.io/_uploads/H1fdh-Qt3.png)



### Presenting the data

If everything is connected correctly, the indicator is green, and the LED lamp is also green if the temperature does not exceed 28 degrees Celsius.

![](https://hackmd.io/_uploads/BJcXC7mYh.png)



And if we interrupt the measurement, then the indicator on the Dashboard  lights up red, and the LED lamp turns off

![](https://hackmd.io/_uploads/BkztCQ7Fn.png)



### Finalizing the design

If everything is connected correctly, the indicator is green, and the LED lamp is also green if the temperature does not exceed 28 degrees Celsius.

![](https://hackmd.io/_uploads/S10FsWXt2.png)

If the temperature exceeds 28 degrees Celsius, then the LED lamp will turn red

![](https://hackmd.io/_uploads/r1rJhWmK2.png)

And if we interrupt the measurement, then the indicator on the Dashboard  lights up red, and the LED lamp turns off

![](https://hackmd.io/_uploads/S1Gb2bXth.png)


**Final thoughts:**

This beginner-level project aims to introduce the concept of the Internet of Things (IoT) to beginners. The main goals of the project are successfully achieved by measuring and monitoring the temperature and humidity in a sauna. Additionally, the project includes a notification feature using the color of an LED lamp when the temperature threshold is exceeded. Please note that the threshold of 28 degrees Celsius mentioned earlier was used for testing purposes at home and may not be suitable for an actual sauna environment. It is important to determine the appropriate temperature range for saunas based on established guidelines and recommendations.

There is potential for further improvement and expansion of the project. One possible enhancement is the integration of a magnetic sensor to track the number of openings and closings of the sauna doors. This can provide additional insights and data about sauna usage patterns.

The ability to control the sauna environment can be especially useful for children or individuals with weakened tolerance to heat. For example, if the LED lamp displays a red color, it indicates that the temperature has exceeded a predefined threshold, and it is necessary to wait for the sauna to cool down before entering. This ensures a safer and more comfortable sauna experience.


================

