---
# System prepended metadata

title: Tutorial on building a basic temperature and humidity system

---

The title of this project is a basic temperature and humidity system. My name is Abhimanyu Kumar with the student ID: ak225gf.

This project is a basic temperature and humidity system which detects the temperature and humidity of a room using sensors.

The time approximation would be 2 hours to 3 hours, depending the different features or triggers added, and perhaps the use of additional sensors.

# **Objective**

I chose this project because I find it troubling to sleep when my room's temperature drops below the standard room temperature (25 degrees celsius) and the humidity goes below 50%, which begins to produce static electricity in my blanket.

Further, checking the temperature of the city does not give me the temperature of the room and using a thermometer does not give me a humidity reading to compare it with. Thus, this basic device would be very handy in reading the data over a period of time and understand the pattern of temperature inside my room and its correlation with the temperature outside.

The new insights this project could give is the applicability of IoT devices in people with sleeping disorders, such as insomnia, or habits.

# **Material**
I bought all of the material listed below as a part of the starter kit from Electro Kit. However, the prices mentioned below may differ from seller to seller.

- **Raspberry Pi Pico W** (70 SEK): This is a microcontroller which has the functionality of supporting 2.6 GHz wireless interface, which also allows the connectivity through many input and output pins.
- **DHT11 Sensor** (55 SEK): This is a temperature and humidity sensor which is used to sense the temperature/humidity data and send it to Adafruit for displaying purposes. It is connected to the microcontroller using a breadboard.
- **Breadboard** (55 SEK): The breadboard is used to build temperary circuits, which in my case, allow the connectivity of the Pico W to the DHT11 sensor.
- **Jumper Wires (Male-to-Male)** (29 SEK): These wires are inserted in the breadboard's input holes, which allow for the sensor to connect to the microcontroller. Since I utilised a breadboard, I only required male-to-male wires.
- **Micro USB Cable** (19 SEK): This cable allows the computer to connect and publish code on the micontroller. The USB end of this cable is connected to the laptop and the other end is connected to the microcontroller.

# Computer Set-Up
The device is programmed using the language MicroPython, which utilises the base of the famous programming language Python but is beginner-friendly and far simpler/easier to use. The IDE which is used is Visual Studio Code, however, the code is uploaded to the microcontroller using Thonny as I found it more user-friendly and easier to use.

How the code is uploaded:
- Use the Pymark extension on VSCode.
- Connect your microcontroller to your laptop through the micro-USB cable.
- Go to the Pymakr extension functionality on VSCode.
- Connect your device to your IDE by pressing on the symbol of a disconnected cable.
- Enter the development mode on Pymakr.
- Press the upload button on Pymakr (it is symboled as an arrow inside of a box, next to the microcontroller).

Steps of installation:
1. Download and install Python, NodeJS (current version), Visual Studio Code IDE and Thonny. Make sure to choose the installation specific to your operating system.
2. Install the PyMakr extension in VSCode.
3. Updating Raspberry Pi Pico W's firmware:
    3.1. On micropython.com, go to Downloads, choose Pico W and download the latest .uf2 file under 'Releases'.
    3.2. Connect the micro USB cable to your computer.
    3.3. While pressing the BOOTSEL button on the microcontroller, connect the other end of the cable to the microcontroller. You can release the button when the microcontroller drive, named RPI-RPI2, appears on your computer.
    3.4. Transfer the .uf2 file, that you downloaded earlier, into this microcontroller drive. This will cause the board to disconnect and reconnect automatically.

# Putting Everything Together
The base of the circuit is the breadboard, which allows all the individual components to easily connect to each other. On the breadboard, there are specific ports which are used for voltage supply and grounding. Although the breadboard is fairly simple to use, one should keep in mind that caution with the voltage supply for a specific sensor must be taken as providing a higher voltage than required can lead to the sensor breaking and malfunctioning. The set-up shown below can be used for both development and production, since the intended use is simple, but hiding certain components could be more beneficial from a safety standpoint.

Below is a basic circuit diagram showing how all the individual components are connected to each other on the breadboard using jumper M-to-M wires:
![](https://hackmd.io/_uploads/BkK_3wyt3.jpg)


# Platform
My choice of platform is Adafruit. This is because it is a beginner-friendly platform which allows for the data to be sent and displayed using a simple MQTT connection (which can be coded with the help of an MQTT library). This platform further allows me to choose different ways of presenting my data, using different forms of visual blocks (such as a graph and a gauge), which makes the interpretation of data far simpler.

# The Code
The project follows a simple, standard file structure in VS Code:
![](https://hackmd.io/_uploads/Syx400SyK3.png)

In the 'lib' folder, we use it to place any of the libraries that we have used or will use in this project, such as the MQTT library. The code for this specific MQTT library has been used with reference to the original authors and is simply utilised for establishing and maintaing an MQTT connection between our device and Adafruit. The secrets.py is a file which contains the name and password of the wifi to which the microcontroller will connect.

The boot.py file contains three primary functions, connect(), http_get() and disconnect(), which are used to connect/disconnect the microcontroller to the wifi. The code inside of boot.py is executed immediately before any other code:
```javascript=5
def connect():
    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(secrets.WIFI_SSID, secrets.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

def disconnect():
    wlan = network.WLAN(network.STA_IF)         # Put modem on Station mode
    wlan.disconnect()
    wlan = None 

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)                           # Sleep for a second
    rec_bytes = s.recv(10000)               # Receve response
    print(rec_bytes)                        # Print the response
    s.close()            
```
The further most important code is contained in main.py. The most important code of this file is comprised in the main() function. This section continuosly retrives and publishes sensor data to the Adafruit feeds, and it further toggles the LED whenever data is read:
```javascript=34
def main():
    client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY, keepalive=60) # This creates an instance of the client and connects to the Adafruit IO server
    client.connect()

    while True:
        global previous_publish
        
        if (time.time() - previous_publish) >= publish_time:
            internalLED.toggle()

            # This is used to retrieve  sensor readings
            sensorReading.measure()
            temperature = get_temperature_reading()
            humidity = get_humidity_reading()
            
            print("Temperature is {} degrees Celsius and Humidity is {}%".format(temperature, humidity))

            # This transfers data to adafruit
            client.publish(AIO_HUMIDITY_FEED, str(humidity))
            client.publish(AIO_TEMPERATURE_FEED, str(temperature))

            internalLED.toggle()
            previous_publish = time.time()
```

# Transmitting the Data/Connectivity
The data is transmitted every 5 seconds, which is the time I chose and specified in main.py as the variable 'publish_time'. The wireless protocol I used is WiFi and used MQTT as the transport protocol.

# Presenting the data
The dashboard is composed of two feeds, namely Humidity and Temperature. The data is saved every 5 seconds. is configured to its transmission every 5 seconds, and can be saved for an indefinite amount of time as Adafruit is free and allows for data saving as long as it is done in their specified limit. This is how the dashboard looks like:
![](https://hackmd.io/_uploads/BJzBzPkY2.png)

# Finalizing the design
![](https://hackmd.io/_uploads/BJVg_DJY2.jpg)
This is a beginner-friendly project, which I made to get an introduction to IoT and how different sensors worked with code. Through this project, I was able to get a thorough basic understanding of how IoT devices work and can serve purposes that bind two or more fields together. For my final thoughts on how this project went, I really enjoyed building this and the simplistic approach I took made me comfortable with working with hardware and further pursue more complex projects in future. For extensions to this project, what could have been done differently could be adding more LED actuators which trigger depending on the specific sensor reading conditions set.