## My IoT-Project! ### Tutorial on how to build a temperature and humidity sensor My name is : Annabelle Dözen Student credentials: ad223mt ## Short project overview The goal for this project was to create a temperature and humidity monitoring system using just one sensor and Rasberry Pi Pico. This system will allow us to measure and track temperature and humidity levels in their enviroment in real-time. This Project can be useful for various applications such as home automation, greenhouse monitoring or weather tracking. **Estimated time for this project was 3-4 hours.** ## Objective The purpose of this project was to monitoring temperature and humidity to gain more hand-on experience in building a practical IoT solution that addresses a common need. I really needed this because im having trouble with the temperature in my appartment, and needed more information on how extream it actually gets when the sun is bursting outside. I got educational values by working with sensors, microcontrollers, and data logging intruduces you a long way in to the basics of IoT technology. This project allowed me to learn a bit about hardware components, data acquisition, software development, and a understanding of the IoT ecosystem. ## Material | component | purpose of | price / Store | | -------- | -------- | -------- | | DHT11| A sensor used for mesuring the humidity in the air asweel as the temperature | 28 SEK / electrokit.com | | Rasberry Pie Pico W| A microcontroller used for data collection, data transfer, and data analysis | 69 SEK / electrokit.com | | Breadboard | A board used to easy connect the sensors without soldering | 34 SEK / electrokit.com | | Jumper wires M/M | Wires for connecting the different components | 24 SEK / electrokit.com | | USB-cable | For connection between computer and microcontroller | 30 SEK / electrokit.com | ## Computer setup **Settin up the IDE:** I choose VSCode and set upp all the necessary plugins to make the system work properly, I use Pymakr plugin. The first step is to updater the firmware for the Rasberry Pi Pico w. Next is to download and install the Node js and i choose VSCode for IDE for this project because its the fastest IDE for produktivitiy. And then add the Pymakr plugin to you VS Code. In order to make this work you have to follow these steps: 1) Install Node Js here **[https://nodejs.org/en](https://)** 2) Install VSCode as the IDE i use in this project, use this **[https://code.visualstudio.com/Download](https://)** to dowload it. 3) Next up is adding the extensions manager from the left panel or by pressing *ctrl+shift+x*, look for **Pymakr** and install it. 4) Now you have to flash your Rasberrypie Pico w and install the latest software. * Go to micropython website and download the latest firmware using this **[https://micropython.org/download/rp2-pico-w/](https://)**. * Now you can open up the webflasher which flashes your device and install the newest firmware. 5) Now connect you device to your computer and go in to VSCode and follow the next steps. * While connecting the micro-usb, holding the **BOOTSEL** key down on the microcontroller to connect your board correctly. Then release the **BOOTSEL** button after you have connected it to your computer. * You will see that a new drive will open up in your file system, which is the Rasberry Pie Pico storage, where you are going to paste over your uf2 file. * Directly after the paste it will automaticy disconnect from your computer, and then get reconnect. its common that you dont see it right away, but it will show up in you choose IDE. ## Putting everything together Below you can see all the connections needed for the DHT11 sensor working. I did a little connection diagram on how everything is connected on to the board, with the sensor and on to the Rasberry Pi Pico W. The black wire goes from GND and its the 38 pin, red wire from the pico goes from 3v3 to plus and then the blue wire from the pico goes from 32 I2C SCL to the first pin of DHT11 that is Vcc with the blue sensor facing left. Then the red wire goes from plus to out in DHT11 thats the pin in the middle. Then the last pin is GND connected to plus. From the DHT11 ![](https://hackmd.io/_uploads/BJQWOgeY3.jpg) ## Platform The platform that i choose for this IoT project is **Adafruit**, it is very beginner-friendly and it seemed to fit just right for the kind of measurements that i have in this project, its very easy visualizing the data in real-time and its easy to understand and read. It offers a variaty of different display choises for the transmitting data. Their is other platforms that i could have used, but i choose **Adafruit** just because it fits my project and the simplicity of it. ## The Code This is the code for the DHT11 in order to have the sensor working on your computer correctly. * Since we are using the MQTT protocol to transmitt and send the data to the platform, we need the MQTT library to be included and added into the library like this. ![](https://hackmd.io/_uploads/By4qKeet2.png) * Then we are starting with the boot.py file in order to get the device access to the internet whenever you start your device. ```python=3 def do_connect(): import network from time import sleep from secrets import secrets 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(secrets["ssid"], secrets["password"]) # 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 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() # Close connection # WiFi Connection try: ip = do_connect() except KeyboardInterrupt: print("Keyboard interrupt") # HTTP request try: http_get() except Exception as err: print("Exception", err) ``` * Then we have to create the main.py file that will contain alla the code that we need to get the data out from the temperature and humidity sensor and forward it to the choosen platform. ```python=2 #import all the necessary libraries import time import dht 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 from machine import Pin # Define pin # Wireless network WIFI_SSID = "Wifi_name" WIFI_PASS = "wifi_password" # Here you could write your own info # Adafruit IO (AIO) configuration AIO_SERVER = "io.adafruit.com" AIO_PORT = 1883 AIO_USER = "username_adafruit" AIO_KEY = "AIO_KEY_ADAFRUTI" AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # Can be anything AIO_TEMPERATURE_FEED = "feeds_temperature" #Here you copy in your own feed adress to connect to adafruit. AIO_HUMIDITY_FEED = "feeds_humidity" # END SETTINGS # Function to publish number to Adafruit IO MQTT server at fixed interval def send_temperature(temp): try: client.publish(topic=AIO_TEMPERATURE_FEED, msg=str(temp)) print("PUBLISHED TEMPERATURE") except Exception as e: print("FAILED") def send_humidity(hum): try: client.publish(topic=AIO_HUMIDITY_FEED, msg=str(hum)) print("PUBLISHED HUMIDITY") except Exception as e: print("FAILED") 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 forevertempSensor.measure() tempSensor.measure() temperature = tempSensor.temperature() humidity = tempSensor.humidity() print("Temperature is {} degrees Celsius and Humidity is {}%".format(temperature, humidity)) send_temperature(temperature) client.check_msg()# Action a message if one is received. Non-blocking. send_humidity(humidity) # Send a number to Adafruit IO if it's time. time.sleep(10) 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 The data is sent using WIFI and MQTT protocols to adafruit. This happens every 10-20 second so that i can see the live temperature and how fast the temperature actually rises. I chose WIFI because it's suitable for indoor temperature and humidity monitoring. It consumes less power, allowing the device to work uninterrupted for a long time. Overall, this approach helps improve performance and ensures reliable operation. ## Presenting the data I used Adafruit to present and store my data. The platform provides all the free users 30 entries/ minute, so it does'nt interupt me sending data every 10-20s for Adafruit to save the database. I will only use three different kind of feeds, even tho Adafruit gives all the free users 5 feeds to use. * Temperature in Celsius * Humidity * Both in one grahp ![](https://hackmd.io/_uploads/rJinGLbK2.jpg) I have also used webhooks to get notified on my Discord when temperature reachs 20 and more degrees Celsius ![](https://hackmd.io/_uploads/B1pRzWxF2.png) ## Finalizing the design I'm very happy that i've been able to learn how to code more with python, i've been doing just a little coding before but nothing like this. And how to actually put hardware together that was a new one for me, this is my first time ever doing anything hands on like this, and i can say that im really happy with the end results i did not belive i even could manage to do somthing like this. I really feel that this course made me a little bit more interested in IoT and the security behind it. I will take everything i've learned and inplement it it my future Cybersecurity training. I see alot of potential in the future! Here is my device that i've been working on for these weeks ![](https://hackmd.io/_uploads/BJTCVWeY3.jpg) ![](https://hackmd.io/_uploads/r1NkH-gFn.jpg)