> This report was written by Abdulrahman Racheed (ar22ree)
This project will gve you a step by step tutorial on how to measure the temperature and humidity by using using the Raspberry Pi Pico W, DHT11 sensor and Adafruit. By following this tutorial you will learn how to:
* How to use sensors to collect and send data
* Visualise the data collected on a website
**Estimated time of completion:** ~4 hours for beginners, ~2 for experienced programmers.
## Objective
My reasoning for choosing this project was to introduce myself into IOT. Ive been interested in working with arduinos my entire life and i though this is a relatively simple, but also informative path to walk that will broaden my knowledge within IOT.
The purpose of this project is to learn about general Internet of things. That includes python, Arduinos, Sensors, collecting data from sensors, sending that data so we can visualise it amongst other things.
This project will give insight about simple python programming, arduino connectivity aswell as sending the collected data via wifi.
## Materials
| Component | Purpose | Website and price |
| --------- | ------- | ----------------- |
|Raspberry Pi Pico WH |The microcontroller for this project|electrokit.com - 109.00kr|
|DHT11|The sensor that is used for measuring the temperature and humidity from the near vicinity|electrokit.com - 49.00kr|
|Breadboard / Kopplingsdäck |A board that lets us easily connect the different components without needing to soulder anything. Can find different prices depending on the number of connections youre looking for, but we're using a breadboard with 840 conections in this project. |electrokit.com - 69.00kr|
|Jumper cables M-to-M|A way of connecting the different parts of the sensors and arduinos together by connecting the cables into the breadboard|electrokit.com - 30.00kr|
|Micro-USB cable|We need a micro USB cable to connect the microcontroller to the PC so we can transfer over our scripts into it.|electrokit.com - 39.00kr|
## Computer Setup
We will be using the Thonny IDE in this project since its optimised and easy to set-up for IOT projects. It makes creating micropython files simple and file trasfer even easier. Here's a step by step guide to help you set up everything.
1: Install python if not already. There are multiple ways to download python, there are many guides on youtube that can help you, but i recommend following [this](https://www.youtube.com/watch?v=AMAE0S_NzxE) one.
* Download [python](https://www.python.org/)
* Run the file and install the software
* Make sure you set the PATH in system variables, the tutorial listed earlier in this section will show you how.
* Open a command prompt, write `python --version` to make sure it has been correctly installed.
2: Download Thonny from https://thonny.org/, make sure you download a compatible version that works on your OS. In my case im using windows, so i downloaded it using the windows link within the website.
3: Install the firmware for your microcontroller
* Download the [MicroPython](https://micropython.org/download/rp2-pico-w/) firmware, make sure not to grab the Nightly Version, but instead latest release.
* While holding down the BOOT button on the micro controller, Connect the micro controller to your computer with the micro usb cable. Release the button after you connected the two.
* You will find a new driver pop up in your file explorer. Transfer the uf2 file you downloaded from the website to your new driver. The microcontroller will automatically disconnect after this step, but do not worry, you will be able to acess it trough Thonny when transfering scripts over to the microcontroller.
## Putting everything together
We will be using this circuit diagram. It shows how the pico, sensor and the cables are set up. It is important to connect them correctly, or else it wont work.

* Firstly you connect the 3.3v pin from the Pico to the VCC pin of the DHT11 sensor. This provides power to the sensor. This is indicated with the red cable.
* Secondly you connect the GP13 pin from the pico to the DATA pin. This connection will allow our scripts to read the data recorded from the sensor.
* We connect our GND pin from the pico to the GND pin on the sensor. This is to ground the circuit and complete it.
## Platform
There is a variety of ways you can display and visualise data from your pico, but we will be using [Adafruit.IO](https://io.adafruit.com/). Adafruit is a free and user friendly website that allows simple data visualisation with graphs, charts and a multitude of other options. We start by creating an account, navigate over to feed and create 2 seperate feeds. One for Temperature, one for humidity. Then you create a dashboard and incorporate those two feeds into it. [This](https://learn.adafruit.com/adafruit-io-basics-feeds) tutorial from adafruit themselves is very helpful, so refer to it if any complications occur.
## Code
For this project we will be using a total of 4 scripts, two of them being libraries. These scripts are boot.py, mqtt.py, credentials.py and main.py. Heres a short description about all the scripts before we get into explaining what we did.
| Script | Purpose |
| ------ | ---------------------------------------------------------------------------------------------------------------------------------- |
| main| main.py will be where our sensors do the work, they will collect data and send the collected data over to our feeds. |
| boot| boot.py is responsible for connecting to the interned trough your wifi. This is so we can send our data to the websites in main.py |
|mqtt|mqtt.py is a library file which has the class that boot.py uses to connect to the internet. Mqtt is a protocol for connecting IOT devices to the web.|
|credentials|credentials.py is a supplementary library for mqtt.py, you fill in your wifi information in there, the mqtt.py script then grabs this information and uses it.|
First we take a look at boot.py since we run that script to connect us to the web. There are three important imports in that file:
```python
import network
import credentials from credentials
import urequests
```
Network is a built in library for using commands specifically for network related work. Credentials is one of our scripts, i will delve further into it later. Urequests is a built in library for handling Urls that we will use for establishing a connection between the script and Adafruit.
When creating the credentials script, make sure to follow this template:
```python
credentials = {
'ssid' : 'your network ssid',
'pw' : 'your network password'
}
```
You can easily find your network SSID by simply searching for it within your computer. To put it simply, SSID is basically your network name. And the password is the same password you use when connecting to the wifi from a phone or laptop.
There are two main functions we use in boot.py. One for establishing a connection to the wifi named ```connect()```, and another for establishing a connection to the website named ```http_get```.
```python=
def connect():
wlan = network.WLAN(network.STA_IF)
if not wlan.isconnected():
wlan.active(True)
wlan.config(pm = 0xa11140)
wlan.connect(credentials['ssid'], credentials['pw']) # import the information from credentials
ip = wlan.ifconfig()[0]
return ip
def http_get(url = 'http://detectportal.operagx.com/'):
popup = urequests.get(url)
println(popup.text)
popup.close()
```
Now that we have the functions written out, we have to execute the code.
```python
try:
ip = connect()
except KeyboardInterrupt as key:
print("DONT TOUCH YOUR KEYBOARD! " + key)
except Exeption as error:
print("error, " + error)
try:
http_get()
except Exception as error:
print("Error establishing a connection to the website, " + error)
```
This block of code tries to execute the predefined functions that we created. If an error occurs, we print out a small message aswell as the bug.
Now we'll take a look at the main.py script.
First we need to create a multitude of variables so we can connect to Adafruit and create a set interval for when our sensors read again.
```python
ADA_server = "io.adafruit.com"
ADA_port = 1883
ADA_user = "Username in Adafruit"
ADA_key = "your adafruit key"
ADA_clientID = ubinascii.hexlify(machine.unique_id())
ADA_humidityFeed = "your username/feeds/humidity"
ADA_temperatureFeed = "your username/feeds/temperature"
latestPublish = time.time()
publishSleep = 10
```
Finding your key is simple. Just navigate to the key icon when logged into your account, press it and copy the key. Paste it in the ADA_key field. This connects your microcontroller to your account and your feeds.
Once the connection to both the wifi and the website have been established, we need to run a continous loop that collects and sends data over to their respective feeds in Adafruit. You can do that by writing:
```python
def main():
#Creates an instance of the client with all the predefined variables above
instance = MQTTClient(ADA_clientID, ADA_server, ADA_port, ADA_user, ADA_key, keepalive=60)
instance.connect()
while True:
global latestPublish
if (time.time() - latestPublish) >= publishSleep:
# Get the readings from the sensors
sensor.measure()
temperature = sensor.temperature()
humidity = sensor.humidity()
# send our readings to the website for visualisation
instance.publish(ADA_humidityFeed, str(humidity))
instance.publish(ADA_temperatureFeed, str(temperature))
latestPublish = time.time()
time.sleep(10)
```
Now you should be able to see continous updates in the website every ten seconds. You can ofcourse change the intervals by changing ```publishSleep``` to whichever time you desire.
## Transmitting Data
We will be using Wifi and MQTT protocols to transmit the data collected by the sensor over to Adafruit. The data is picked up and published every 10 seconds here, but as stated, it can be changed to whatever you desire. This will provide you a live feed with the current readings and it can detect drastic changes in temperature and humidity over a short period of time.
## Presenting Data
Adafruit has a nice built in dashboard with a variety of different ways to display your feeds. You can link your feeds to the created dashboard, and pick out a way to display them. [This](https://learn.adafruit.com/adafruit-io-basics-dashboards) tutorial from Adafruit can help if any confusion occurs. I selected two gagues to present the current humidity and temperature, and two line charts to track changes over time as seen below.

Since i am using Adafruit, i have to abide by their Data policies. Their database stores information up to 30 days per feed, so it is only able to give a review of values recorded over 30 days. For this course, that amount of time was enough. But if i were to create a project that needs to track small changes over a large period of time, this would be an issue.
## Finalizing the design
This course has provided me a great learning experience. I encountered many difficulities but that helped me grow as a programmer. I enjoy courses that encourage you to think for yourself and problem solve, while still having access to help if needed. And this course has really improved my critical thinking aswell as problem solving. One idea i have for the future is to connect the microcontroller to a fan or some sort of air conditioning. If it gets to warm, it turns on the fan. If its too cold, then turn on air conditioning, or turn off the fan (depends on the temperature). Perhaps another update i will do in the future is to set it up to my own local database so i am not constrained to simply 30 days of data saved. I want to track drastic changes over a long period of time.
