# Tutorial: How to change the colour of lights depending on temperature and humidity
Elin Svensson (es226ew)
## **Introduction**
This project aim to create a system that makes a light glow in green, yellow or red depending on the temperature and humidity. This is achived by using one sensor to sense temperature and humidity and three LED lights. The system is using WiFi to connect with the service and Ubidots as the database. Ubidots is a good choice since it´s easy to use and you can easily scale up your project without having to build a new infrastructure.
The project might take between one or three hours to completet depending on experience.
## **Objective**
I'm a Product developer and have a degree in Product development with furniture design. I have an interest for technology and would therefore like to combine this in a project which I could further develop in the future.
The project is designed to easily keep track of whether the temperature and humidity is within a certain range. For instance, to ensure that the environment is comfortable for an office workspace.
Since the data (temperature and humidity changes) is stored in the database, this can provide insights into variations over time, while also providing real-time indiaction through the color of the light.
## **Material**
| | Item | Link | Price (SEK) | Quantity needed |
| --------------------------------------------- | -------------------- | ---------------------------------------------------------------------------------------------------------- | ----------- |:--------:|
|  | Breadboard | [Electrokit](https://www.electrokit.com/en/product/solderless-breadboard-840-tie-points-2/) | 69 | 1 |
|  | Raspberry Pi Pico WH | [Electrokit](https://www.electrokit.com/en/product/raspberry-pi-pico-wh/) | 109 | 1 |
|  | USB Cable | [Electrokit](https://www.electrokit.com/en/product/usb-cable-a-male-micro-b-male-30cm/) | 19 | 1 |
|  | DHT11 | [Electrokit](https://www.electrokit.com/en/product/digital-temperature-and-humidity-sensor-dht11/) | 49 | 1 |
|  | LED Red | [Electrokit](https://www.electrokit.com/produkt/led-5mm-rod-diffus-1500mcd/) | 5 | 1 |
|  | LED Yellow | [Electrokit](https://www.electrokit.com/produkt/led-5mm-gul-diffus-1500mcd/) | 5 | 1 |
|  | LED Green | [Electrokit](https://www.electrokit.com/produkt/led-5mm-gron-diffus-80mcd/) | 5 | 1 |
|  | Resistor 330 ohm | [Electrokit](https://www.electrokit.com/produkt/motstand-kolfilm-0-25w-330ohm-330r/) | 1 | 3 |
|  | Jump Wire | [Electrokit](https://www.electrokit.com/produkt/labbsladd-20-pin-15cm-hane-hane/) | 29 | 10 |
To carry out the project I have used the materials metioned above. A breadboard is used to easily connect the various sensors to the device. The Raspberry Pi Pico WH which is programmed by MicroPython is used as the microcontroller. It´s easy to handle and has many digital and analog input and outputs which is suitable for this kind of project. It´s connected to the computer via the USB cable.
A DHT11 sensor is used to measure temperature and humidity. It´s range is between 0 - 50 degrees Celsius and 20 - 90 percentage of humidity. A red, yellow and green LED light are used to indicate the current temperature and humidity range. To limit the current passing through the LEDs and prevent possible overcurrent or overheating, resistors are used. In this case 330 ohm resistors. All components are connected to the device using jumper wires.
## **Computer setup**
For development IDE I´ve used [Visual Studio Code ](https://code.visualstudio.com/Download), which support Pymakr, an extension that makes it possible to develop with MicroPython. To enable the use of additional functions and tools, [Node.js](https://nodejs.org/en) is also downloaded.
Follow these steps for the basic installation of the development environment:
**1.** Download and install Node.js. Make sure to download **CURRENT** and not **LTS**.
**2.** Download and install VS Code.
**3.** Open VS Code and via the *Extensions manager* search for Pymakr and install it. If you want a more detailed explanation, follow [this link](https://github.com/pycom/pymakr-vsc/blob/HEAD/GET_STARTED.md).
To install firmware follow these steps:
**1.** Download the [micropython](https://micropython.org/download/rp2-pico-w/) firmware, it's a **uf2** file. Make sure to downloard the latest from **Releases**.
**2.** Pluggin the micro USB to Raspberry Pi Pico.
**3.** Hold down the BOOTSEL button on Raspberry Pi Pico while plugging in the USB to the computer.
**4.** A new drive will appear in your file system named **RPI-RP2**, move the **uf2** file there.
**5.** Wait for the board to atomatically disconnet and reconnect.
## **Putting everything together**

## **Platform**
I have chosen Ubidots because of its simplicity, adaptability and cloud-based availability. It provides me with the functionality and flexibility I need to successfully carry out my IoT project.
Create an account at [Ubidots](https://ubidots.com/). Then create a device and two variables, one for temperature and one for humidity. If you want more detaild explanation, follow this [link](https://help.ubidots.com/en/articles/1658666-connect-a-fipy-pycom-board-to-ubidots).
## **Code**
Below is the code for this project. To facilitate setup, write the code for Wi-Fi connection in `boot.py` since it needs to run on boot to make the remaning code work.
```Python=
import network
WIFI_SSID = "WIFI_SSID"
WIFI_PASSWORD = "WIFI_PASSWORD" #Your WiFi Cridential
def connect_to_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi-network...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print("Connected to WiFi:", wlan.ifconfig()[0])
connect_to_wifi()
```
The remaining code is written in `main.py`.
Following is a explanation of the code:
First make the import statements, to make the various functions and classes available in the code and use them to interact with the DHT11 sensor, control pins, and make HTTP requests.
Then create variables and assign them values to control and interact with the connected sensors.
An object named "myPin" is created to utilize the value from the variable "dataPin". "PinOUT" is used to configure the pin as an output, meaning it is used to control or send signals to a device. "Pin.PULL_DOWN" is used to enable a pull-down resistor connection on the pin, which helps stabilize the signal and prevent interference.
Furthermore, an instance of the DHT11 class is created and assigned to the variable "sensor". "myPin" is used as an argument, which means it assigns the specific pin that the DHT11 sensor is connected to the sensor. This allows the usage of the "sensor" instance in the code.
Three Pin objects are created to control the LED lights in different colours by assigning them the pin numbers they are connected to and configuring them as outputs.
Retrieve the values from Ubidots in order to send temperature and humidity data to the correct variables in the Ubidots platform.
Create the code that makes an HTTP-POST request to Ubidots to report the temperature and humidity to the platform.
'url' is the web address to the Ubidots API.
'headers' is a dictionary that contains the HTTP headers for the request.
'data' is a dictionary that contains the temperature or humidity value being sent to the Ubidots platform.
'response' is the variable that holds the response from Ubidots after the request is sent. Use urequests.post() to send the request with the URL, data, and headers.
After the request is sent, close the response using 'response.close()'.
Create an infinite loop ('while True') to continuously read the temperature and humidity. 'sensor.measure()' is used to measure the values.
'tempC = sensor.temperature()' assigns the temperature (in Celsius) that was read to the variable 'tempC'.
'hum = sensor.humidity()' assigns the humidity that was read to the variable 'hum'.
'print(tempC, hum)' prints the values to observe them.
'time.sleep(60)' pauses the code for 60 second before the next reading to avoid overloading the sensor.
After the sensor data has been read, three conditional statements ('if' statements) are performed to check the temperature and humidity values and control the LED lights based on specified conditions. The specified values for this project are based on research of the optimal temperature and humidity values for an office environment.
If the green light is lit, it means the temperature is between 20-26 degrees Celsius and the humidity is between 40-60 percent, which is considered optimal.
If the yellow light is lit, it means the temperature is between 18-19 degrees or 27-28 degrees Celsius and the humidity is between 40-60 percent, indicating that the temperature is either to low or to high.
If the red light is lit, it means the temperature is below 17 degrees or above 29 degrees Celsius, or the humidity is below 40 percent or above 60 percent. This indicates that the temperature or humidity is either too low or too high.
Lastly, the functions "report_temperature_to_ubidots(tempC)" and "report_humidity_to_ubidots(hum)" are called to report the temperature and humidity to the Ubidots platform.
```Python=
from dht import DHT11
from machine import Pin
import time
from time import sleep
import urequests # Import Statements
dataPin = 28
greenLED = 3
yellowLED = 9
redLED = 15 # Variables and Values
myPin= Pin(dataPin,Pin.OUT,Pin.PULL_DOWN) # Create "myPin" to utilize the value from the variable "dataPin"
sensor=DHT11(myPin) # Instance of the DTH11 and assigned as sensor
myGreen= Pin(greenLED,Pin.OUT)
myYellow= Pin(yellowLED,Pin.OUT)
myRed= Pin(redLED,Pin.OUT) # Three Pin objects to controll the LED
UBIDOTS_TOKEN = "API_TOKEN"
VARIABLE_ID_TEMPERATURE = "VARIABLE_ID_TEMPERATURE"
VARIABLE_ID_HUMIDITY = "VARIABLE_ID_HUMIDITY" # Ubidots values
def report_temperature_to_ubidots(temperature):
url = "http://industrial.api.ubidots.com/api/v1.6/devices/default_device"
headers = {"X-Auth-Token": UBIDOTS_TOKEN, "Content-Type": "application/json"}
data = {VARIABLE_ID_TEMPERATURE: temperature}
response = urequests.post(url, json=data, headers=headers)
response.close()
def report_humidity_to_ubidots(humidity):
url = "http://industrial.api.ubidots.com/api/v1.6/devices/default_device"
headers = {"X-Auth-Token": UBIDOTS_TOKEN, "Content-Type": "application/json"}
data = {VARIABLE_ID_HUMIDITY: humidity}
response = urequests.post(url, json=data, headers=headers)
response.close() # Make an HTTP-POST request to Ubidots
while True:
sensor.measure()
tempC=sensor.temperature()
hum=sensor.humidity()
print(tempC,hum)
time.sleep(60)
if (20<=tempC<=26 and 40<=hum<=60):
myGreen.value(1)
myYellow.value(0)
myRed.value(0)
elif (18<=tempC<=19 or 27<=tempC<=28) and 40<=hum<=60:
myGreen.value(0)
myYellow.value(1)
myRed.value(0)
else
myGreen.value(0)
myYellow.value(0)
myRed.value(1) # Three conditional statements to control the LED lights
report_temperature_to_ubidots(tempC)
report_humidity_to_ubidots(hum) # Report value to Ubidots
````
## **Connectivity**
Every minute, data is sent to Ubidots via WiFi and HTTP protocol. This is a reasonable interval as the temperature and humidity don't change significantly within such short period of time. At the same time, it provides a good collection of data for long-term monitoring and analysis.
## **Presenting the data**
I created four widgets on the dashboard to easily read the collected data. The data is saved every 60 second to the database.

## **Finalizing the design**
I am satisfied with my project and feel that I have achieved my initial goals successfully. To further enhance the project and create a more practical solution, I would like to connect a physical lamp in my home.


