# Project report - Humidity as a proxy for coffee brewing completion
### Author: Tobias Kontio (tk222ma)
## Introduction
This is both a report and a tutorial on how to use sensor data from a DHT11 Digital Humiditiy and Temperature sensor to interpret whether a coffee machine is done brewing or not. It acts as an introduction to the field of IoT and is aimed at beginners with very basic knowledge of coding, electronics, IT and IoT in general.
The estimated time required for this project is 3-6 hours, assuming extremely limited prior knowledge.
## Objective
The specific project was intended as a way for me to get a basic introduction to the fields mentioned in the introduction. As I am a complete beginner, I figured this would be a great way to wrap my head around the covered concepts and the teaching material in the course 1DT305 at LNU. This will act as a baseline for further development and prototyping.
The project is suitable for a beginner in IoT to get a paced introduction to the basic concepts of IoT and they can follow along in practice at a low cost. The setup works well for impatient students who need coffee often at home while working, but who have a low attention span and easily burn the coffee, rendering it bitter. The dashboard allows the person to monitor and visually see when the coffee is expected to be done, allowing them to return to the room where the coffee is being made before it is ruined.
After completing the project, I expect the individual to have gained basic knowledge in electronics, microcontrollers, breadboards, programming, and IoT fundamentals.
## Material
**Rasperry Pi Pico W (Pico W) - microcontroller (MCU) from Electrokit**

The Rasperry Pi Pico W is a microcontroller which has WiFi capabilities. It is very afforable and is currently the best option, in my opinion, for this project. It is the computational device I've chosen as it came in the recommended startet kit for the course of 2023 and has served its purpose splendidly.
**Breadboard from Electrokit**

Breadboards are a tool to prototype with electronics. The holes on the plastic board are connected in rows allowing current to flow. Using wires and other tools, electrical circuits can be made without having to commit to soldering or other permanent solutions. I *HIGHLY* recommend these as a prototyping tool and am very happy that I've been exposed to them in this project. They were a bit daunting at first, like everything else, but have proven to be a friend not foe.
**USB A - MicroUSB Cable from Electrokit**

The cable is used to connect the Pico W to the computer in order to run code on the Pico W and also to upload the code to the Pico W so that it can run it even when not plugged into the computer.
**DHT11 Sensor (41015728) from Electrokit**

The sensor used to collect data is a **D**igital **H**umidity and **T**emperature sensor, hence **DHT**, and can collect both thermal readings as well as the humidity of the surroundings. In this project I only utilize the humidity component to determine if there is steam coming off of the coffee machine and infer whether the machine is done or not.
**Jumper Cables - M/F & M/M from Electrokit**

In order to wire the device I use male-male (M/M) jumper cables, the male-female (M/F) cables are used to wire the sensor and make its position more flexible. The three uses are voltage, data, and ground.
**Computer**
A computer is needed to program the device and to make a user interface (UI) for the user to interpret the visualized data from.
**Wi-Fi connection**
In order to send the data, Wi-Fi is used and so a router that supports it is needed for the project. It will be the basis for the Pico W to send data to be visualized.
**Vendor**
You can, at the time of writing, get all the components from Electrokit.com, well recommended, aside from your personal artifacts such as the computer and router which are assumed to already be in your possesion.
If you intend to apply what you learn in this tutorial to future projects, as I do, then I would recommend a sensor kit. Mine was a 25 piece which included the DHT11 sensor used and the kit was priced at 299 SEK. The remaning components were accuired through the Start kit for the price of 399 SEK. These were selected soley off of the fact that they were presented on the *Bill of materials* list for the year 2023.
## Computer setup
The integrated development environment (IDE) that I selected was VS Code. While I had not been coding much before, I was familiar with VS Code and it was therefore the only sound choice I could make. I would not claim I know my way around it or any IDE, which means this is a good option as I could complete this project in this environment.
If you do not already have it installed, then the first thing to do is to install Node js. It is needed to have everything run and so you need to download it [**(here)**](https://nodejs.org/en/). Select the version that is labeled "Recommended For Most Users" and when the download is complete, run it.
With that out of the way it is time to get the actual IDE. Download VS Code [**(here)**](https://code.visualstudio.com/Download), select your operating system and install it.
Once you have it installed you need something called an extension. It is like an add-on to VS Code where you can interact smoothly with the Pico W and fortunately, it is very easy to do.
When you open the VS Code, on the left bar of icons, look for the stack of squares, click it.
In the search bar, enter "pymakr", click the first result and install the extension by clicking install.
The newest versions had some issues and so I decided to use version 2.22.5.
After it is done installing you can verify the installation by finding the new pymakr icon in the bar on the left.
*If you have any trouble, LNU has made an excellent tutorial [**(here)**](https://hackmd.io/@lnu-iot/rkiTJj8O9).*
You then create a project and a file which you name "main.py" in which you will write your code. The naming is important so that the preprogrammed internals of the Pico W know that the file is intended to be used on there. The code will then be put on the board using the USB-A to microUSB cable.
The Pico W takes MicroPython as a language, and it is a great way to start programming. Python, on which it is based, was made to be a language for the programmer rather than for the machine, making it slower to run but much easier to write and read for humans. MicroPython is therefore a great way to start coding as it is essentially a light version of Python!

Next you will need to fetch a file to flash the Pico W, ensuring that it is set up and ready to go! You need to get the file from **[here](https://micropython.org/download/rp2-pico-w/)** and then, once the preparations for the Pico W described under "putting everything together" are completed, hold down the bootcell button plug-in the Pico W while holding it down and then drag the flash file onto the folder for the Pico W.
*Details for this procedure can be found on **[this tutorial](https://hackmd.io/@lnu-iot/rkFw7gao_)** by LNU.*
## Putting everything together
Let's start! If you have a optional Electrostatic-discharge (ESD) bracelet, now is the time to put it on and ground yourself (and potentially your work surface). Bring out your breadboard and your Raspberry pi pico W. You will likely find a black sponge on the underside of the Pico W, it is there to prevent ESD during shipping, remove it at this time.
Identify the microUSB connector on the Pico W and face it away from the breadboard. Align the pins on the underside with the holes on the breadboard and press the Pico W down into the breadboard. Some resistance is expected, but when done the Pico W will sit almost flush with the breadboard.

Open [**(this)**](https://picow.pinout.xyz/) to find a pinout diagram for the Pico W, refer back to it often to ensure your connections are correct.
Next find two M/M jumper wires and connect them to the positive and negative terminals respectively.

Using the pinout diagram as a guide, connect the negative cable to "Ground" at Pin 38. Then connect the positive wire to "3v3 Out" at Pin 36.

You now have a way to get power through the breadboard through these wires! Great job!
Grab two more M/M jumper wires and insert them in the positive and negative terminals respectively, keeping some space to the other wires so things do not get tangled and it is easy to access.

Bring the other ends to the middle area of the board and attach them next to each other, NOT IN THE SAME ROW! this would short your circuit!

Next grab two M/F jumper wires, in the same colors as the previous pair if you have them but any two colors will do really.
In the same two rows as in the middle area of the breadboard as the previous two wires, connect the male ends to the breadboard. You are now able to feed power through the terminal to whatever you attach on the female side of these two cables.

So what do you want to power? The DHT11! Find the sensor in the kit and refer to the picture on the packaging to make sure you got the right one. On the board that the sensor sits on, next to one of the pins, you will find the letter "S" for signal, you will stay away from this pin for now.
The other two pins are "power" and "ground" and you need to be careful to connect the correct pin to the correct female connector. The positive lead goes to the middle pin. The negative lead goes to the pin on the side that does NOT have the "S" printed on its side.
1. Double check the wiring.
2. Good! Triple check the wiring.
3. Good. Are you sure you did it right? You could fry your sensor if they are reversed, so give it one last look-see if you are unsure.
The setup can now feed power to the sensor but you have no way of getting any data, you are only supplying electricity at the moment. So finish the last part of the wiring.
Find another M/F jumper wire and connect the female port to the sensor, this time where the "S" is printed, so that you can read the measurements. Connect the male end next to the other two jumper wires on the breadboard which are connected to the sensor. Now the sensor has a path to send data, you need to lead it to a port where the Pico W can read it.

Grab another M/M jumper wire and connect it next to the two jumper wires in the middle, in the same row as the signal wire from the sensor.

Refer back to the pinout diagram and connect the other end of the jumper wire to Pin 32. That is it! Wiring, all done! Great work!

A schematic is provided for additional clarity. The only real difference is that the sensor in the image is connected directly into the breadboard, whereas the one you have put together is free to move thanks to the M/F wires.

## Platform
Before you can write the code you need to set up a platform for the data to be sent to, else the data have nowhere to go. For this you will use Ubidots. It is free to use for your purposes but if you would like to expand on the capabilities there is a credits system where you can buy your way to additional features. It is based on the cloud and will, due to the above, work great for this project.
You can create an account [**here**](https://ubidots.com/stem), be sure to read everything before you agree, as no accountability can be ascribed to me, it is you and you alone who are entering an agreement with anything you sign or agree to.
Once you have your account you can start setting up your "Dashboard" to show the data. you will gather the data over what is called HTTP request and visualize them on what are called widgets. Following this [**link**](https://stem.ubidots.com/accounts/signin/), you can sign in to your account with the credentials you entered when you signed up.
## WiFi Setup
Security with tech is a big concern and IoT is far from special in this regard. It is often the case that the components or devices used for IoT projects and products do not go through the same rigorous security measures as other IT products. It is therefore **HIGHLY RECOMMENDED** that you create a seperate guest network for your IoT devices and projects, **and make sure it does not have access to the rest of your network**. This tutorial does not cover this in practice and it is most likely not sufficiently secure to rely on, and most likely introduces vulnerabilities in your network. I just would not feel right writing a tutorial like this without mentioning the hazards.
That said. This step is optional but again **HIGHLY RECOMMENDED**.
## The code python
Since the tutorial is intended for beginners, I'll just briefly comment on the parts of the code. This code is all placed in a single "main.py" file to run correctly.
The first part is to ensure you have the needed components for you code. You import it by typing "import" and then the library name you need. If you want to save space you can type "from" followed by the name of the library "import" followed by the name of the function. This lets you fetch the part you need and leave out the rest. Additionally, if you want to call what you import something else, you can import it "as" something else.
```python
import network
import urequests as requests
import machine
from time import sleep
import random
import dht
```
Next in coding, you need to make your definitions. You type out a name and use the equal sign to express what is meant by the variable. In this case it is strings, text put simply, and enclose it in " ". A variable named "DELAY" is made and holds the number 5 as well as a pin on the Pico W being defined for use. Pin 27 has been selected and it refers to I/O pin 27, which is placed on the physical pin 32. Refer back to the pinout diagram from before and investigate this, it can be confusing.
```python
TOKEN = "Your-specific-token" #Put here your TOKEN
DEVICE_LABEL = "Your-label-for-the-device-which-you-set-up-on-ubidots" # Assign the device label desire to be send
VARIABLE_LABEL = "Your-label-for-the-sensor-which-you-set-up-on-ubidots" # Assign the variable label desire to be send
WIFI_SSID = "Your-WiFi-SSID" # Assign your the SSID of your network
WIFI_PASS = "Your-WiFi-Password" # Assign your the password of your network
DELAY = 5 # Delay in seconds
tempSensor = dht.DHT11(machine.Pin(27)) # DHT11 Constructor
```
Next is to define the functions, the stuff that will use what we have defined. If you do not understand any of this copy-pasting should work fine.
```python
# Function for WiFi connection
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(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
# Builds the json to send the request
def build_json(variable, value):
try:
data = {variable: {"value": value}}
return data
except:
return None
# Sending data to Ubidots Restful Webserice
def sendData(device, variable, value):
try:
url = "https://industrial.api.ubidots.com/"
url = url + "api/v1.6/devices/" + device
headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"}
data = build_json(variable, value)
if data is not None:
print(data)
req = requests.post(url=url, headers=headers, json=data)
return req.json()
else:
pass
except:
pass
```
Lastly, the main code, the stuff that runs it all the hundreds of lines of incomprehensible.... yeah no it is just this brief stuff below. Half of it is comments and does not even do anything... If you would prefer to measure with temperature I left that bit in there in case you want to uncomment it for any reason.
```python
# Connect to the WiFi
connect()
# Your device sends a registered sensor value between 0 and 100 every five second to Ubidots
while True:
tempSensor.measure()
# value = tempSensor.temperature()
value = tempSensor.humidity()
returnValue = sendData(DEVICE_LABEL, VARIABLE_LABEL, value)
sleep(DELAY)
```
What is worth noting is that all the information is placed in the same file, keeping everything close and easy to find. Great for a beginner, but also easy for a beginner hacker to work around. This setup is not a safe way to store your credentials and should be improved on drastically if meant to be implemented.
## Transmitting the data
The Pico W connects to WiFi according to the SSID and Password that you have provided it. The device takes a measurement of the humidity and sends it, after which it enters a 5 second delay to give pause and room to breathe for the system before looping around and doing it over and over. The system uses HTTP request and the data is sent to the Ubidots Rest API.
*A quick note is that the choices made here are of relevance to electrical consumption. WiFi is quite costly and would drain batteries fast. When deploying I therefore use a 5V phone charger*
## Dashboard
The Dashboard is where the data will be visualized. It is done using what Ubidots calls widgets and it is very intuitive. You simply set up an account, click "Devices", click the blue plus on the right to add a new blank device, and name it! Enter your new device and click "Add Variable" and add a "Raw", name it alarm and another and name it sensor. Next go to "Data" and click "Events". Click the blue plus and select the sensor value to be greater than 70 and name it well. Create another but make its condition equal or less than 70. Next go to "Data" and then "Dashboards" and click the blue plus. Add a "Gauge", add variable, select your Pico W, select the sensor, and save it. Create an indicator the same way that you link to the alarm. When you run the code on your Pico W the registered values will turn up here. Your device now has widgets set up, and it is done!
The data are now updated anytime they are sent to the platform and the graphics can update in real time! Expect some delay though, I mean the data are going to frigging space!?
*Once again LNU has created an excellent [**tutorial**](https://hackmd.io/@lnu-iot/r1k63jjwo) on how to set up widgets on Ubidots. Refer to it if there are any problems*
## Finalizing the design

The 0-100 meter will tell you how much humidity the coffee machine is giving off and you can assume that when it is inactive, you should register ambient values. When it is running you should register high concentrations of water and the number will be closer to 100. When the number decends again it is safe to assume the coffee machine is no longer giving off any steam and diffusion is letting the air slowly return to ambient levels.
There is a boolean toggle to let you know if the coffee machine is still brewing and when it turns back to green it is done brewing, and you should go get your fresh coffee before you forget and have to be sad for the coming hour drinking bitter, burnt coffee.

In practice, I decided to utilize a metal ruler and masking tape to get in position to detect the steam, the system works well and I get reliable readings that ensure my coffee is served at just the right time.
Depending on your coffee setup your fastening and placement will likely vary, try what works and enjoy your next cup!
## Take away
This project has been one of the most educational experiences of my life. I have not learned so many new things and been so challanged in a very long time. The course 1DT305 at LNU has exceeded all my learning expectations and I could not be happier.
As I mainly wanted to get started and have a first look into the world of IoT and the possibilities within it and its subfields, I really am proud with this project. It might not look like much, it was a basic project, but to me it has been the catalyst I needed to become a better and more versatile engineer. It has given me the base to start building on, and I literally cannot wait to start my next project! Thank you TAs, teachers, lecturers and every single student, this might very well have been the best course I've attended and it was all thanks to you!