---
# System prepended metadata

title: Bedroom Weather Guardian

---

Noor Abo Hasan na223f
Course Introduction to Applied IoT, Summer 2023

---
## Project overview
The "SleepWeather Monitor" is a project aimed at monitoring weather conditions in a bedroom during sleep hours using a Raspberry Pi Pico W microcontroller. The project utilizes sensors such as the DHT11 for temperature and humidity measurements and a photoresistor to measure light intensity in the room. The Raspberry Pi Pico W collects data from these sensors and communicates it to the Ubidots platform.
The project's estimated time is two to four hours, depending on the reader's skill level and the time dedicated to it.

---
## Objective

I have chosen to build the Indoor Weather Guard device because I want to address my wife's concerns about the bedroom environment. The purpose of this device is to monitor the temperature, humidity, and light intensity in our bedroom and provide valuable data for analysis.

With the collected data, I aim to understand how these environmental factors impact our sleep quality. By analyzing the data, I hope to gain insights into the optimal temperature and humidity levels for a comfortable sleep environment. Additionally, I want to assess the correlation between light intensity and our sleep patterns.

This project will provide valuable insights that will help us make informed decisions about improving our bedroom environment. By understanding the impact of these factors on our sleep, we can make necessary adjustments such as adjusting the thermostat, using humidifiers, or implementing better lighting solutions. Ultimately, the goal is to create a more comfortable and conducive sleep environment that meets our specific needs and enhances the quality of our sleep.

---
## Material
### The materials used in this project:

1- Raspberry Pi Pico: It is a microcontroller board with GPIO pins that can be used to connect sensors and collect data.

Specifications: Microcontroller RP2040, GPIO pins, programmable in MicroPython or C/C++, etc.

2- DHT11 Temperature and Humidity Sensor: It is a basic sensor that measures temperature and humidity.

Specifications: Temperature range (-20 to 60°C), humidity range (20-90% RH), 1-wire digital interface, etc.

3- Light Dependent Resistor (LDR): It is a sensor that measures light intensity.

Specifications: Resistance changes with the amount of light, analog output.

4- Resistor: A resistor of 10k ohms used to limit the current flow in a circuit and protect the LDR.

5- Breadboard and Jumper Wires: Used for prototyping and connecting components.


6- USB Cable: Used to connect the Raspberry Pi Pico to a computer or power source.




| Component | Photo |
| --------- | ----- |
|   Raspberry Pi Pico        |    ![](https://hackmd.io/_uploads/B1CLABkY3.png)|
| DHT11 Temperature and Humidity Sensor| ![](https://hackmd.io/_uploads/r175ArJYn.png)|
|Light Dependent Resistor (LDR)|    ![](https://hackmd.io/_uploads/Hkzk1UJYn.png)|
|      Resistor      |   ![](https://hackmd.io/_uploads/r1uWJ8kK2.png)|
|  Breadboard  |   ![](https://hackmd.io/_uploads/HkvB1IkKh.png)|
|Jumper Wires        |  ![](https://hackmd.io/_uploads/SyTOJIJF2.png) |
| micro-USB cable     | ![](https://hackmd.io/_uploads/B1O0k81tn.png)|

I acquired all the materials as part of a Start Kit - Applied IoT, which I purchased for approximately 400 SEK. The kit provided a convenient solution as it included all the necessary components required for my project. It saved time and ensured the compatibility of the components.

---
## Computer Setup

For programming the Raspberry Pi Pico microcontroller, I utilized the following setup:

1- Installation of Node.js:

As a prerequisite for some of the tools and dependencies used in the project, I installed Node.js on my MacBook.
I visited the official Node.js website (https://nodejs.org) and downloaded the latest stable version for macOS.
After downloading the installer package, I ran it and followed the on-screen instructions to complete the installation of Node.js.


2- IDE: Visual Studio Code (VS Code) with PyMakr extension

I chose Visual Studio Code as my Integrated Development Environment (IDE) for its user-friendly interface and excellent support for Python and MicroPython development.
I installed the PyMakr extension in VS Code, which provides convenient features specifically designed for working with microcontrollers like the Raspberry Pi Pico.

3- Installation of VS Code and PyMakr:

I downloaded and installed Visual Studio Code from the official website (https://code.visualstudio.com).
Once installed, I launched VS Code and installed the PyMakr extension from the Visual Studio Code marketplace.
The PyMakr extension allows seamless interaction with microcontrollers and provides features such as code editing, uploading, and debugging.

4- MicroPython Firmware:

I flashed the MicroPython firmware onto the Raspberry Pi Pico microcontroller to enable programming it using the Python language.
To flash the firmware, I followed similar steps as mentioned before:
a. Downloaded the latest stable MicroPython firmware from the official MicroPython website (https://micropython.org).
b. Connected the Raspberry Pi Pico to my MacBook using a USB cable.
c. Pressed and held the BOOTSEL button on the Pico while connecting it to enter the bootloader mode.
d. The Raspberry Pi Pico appeared as a mass storage device on my computer.
e. I copied the downloaded MicroPython firmware file onto the Pico's mounted drive.
f. After copying, I disconnected and reconnected the Pico to start running the MicroPython firmware.

5- Configuring PyMakr:

To configure PyMakr for Raspberry Pi Pico development, I followed these steps:
a. Opened the PyMakr extension in Visual Studio Code.
b. Configured the PyMakr settings to specify the board type (Raspberry Pi Pico), serial port, baud rate, and other relevant options.
c. Verified the connection between VS Code and the Raspberry Pi Pico by checking the status in the PyMakr console.

6- Writing and Uploading Code:

With the setup complete, I could write Python code for my project and upload the code to the Raspberry Pi Pico.

---
## Putting everything together

The setup of the device and the wiring is shown in a circuit diagram in this Figure:

![](https://hackmd.io/_uploads/BJ8WXKkt3.png)

Wiring Connections:

I connected the Raspberry Pi Pico to the breadboard using jumper wires.
For the DHT11 temperature and humidity sensor, I connected the VCC pin to the 3.3V power rail, the GND pin to the ground rail, and the data pin to a GPIO pin on the Pico.
For the light-dependent resistor (LDR), I connected one leg to the 3.3V power rail and the other leg to a GPIO pin on the Pico. I also added a resistor in series with the LDR to create a voltage divider circuit.
I made sure to connect the ground (GND) of the Pico to the ground rail on the breadboard.

## Platform
In my project, I chose to use Ubidots as the platform to visualize and analyze the collected sensor data. After comparing different options like Thingspeak and Blynk, Ubidots stood out for its user-friendly interface, comprehensive documentation, and IoT-focused features. It is a cloud-based platform, offering easy accessibility from anywhere. I started with the free plan, but Ubidots provides paid subscription plans for scaling up. With Ubidots, I can create interactive dashboards, set alerts, perform data analysis, and integrate with other services. It's an ideal choice for my project's needs.

---
## Code

The code for this project has been divided into three separate files: secrets. py, boot. py, and main. py. This modular approach helps organize the code and enhances readability and maintainability.

1- Secrets. py: This file contains sensitive information such as the Wi-Fi network credentials. It is used to store this information separately from the main code for security purposes. By keeping the sensitive data in a separate file, it can be easily updated without modifying the main code. The secrets. py file is not shared publicly or included in version control to protect the sensitive information.



```
secrets = {
    'ssid': 'Your_WiFi_SSID',
    'password': 'Your_WiFi_Password'
}
```
2- boot. py: This file handles the Wi-Fi connection and network setup. It imports the necessary libraries and functions, including the do_connect() function, which establishes a connection to the Wi-Fi network using the credentials from the secrets .py file. It also includes the http_get() function for making HTTP requests to a specified URL. The boot .py file ensures that the device is connected to the Wi-Fi network and can communicate with other services or devices.

```
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)

```
3- main. py: This file contains the main code logic for reading sensor data, processing it, and sending it to Ubidots, a cloud-based platform for IoT applications. It imports relevant libraries and initializes the GPIO pins for the sensors. The read_sensor_data() function reads the temperature, humidity, and light intensity values from the DHT11 sensor and the photoresistor. The send_data_to_ubidots() function sends this data to Ubidots using a POST request to a specified URL. The main loop continuously reads sensor data, prints it to the console, and sends it to Ubidots at regular intervals using the utime.sleep() function.

```
import machine
import dht
import utime
import urequests

# Define GPIO pins
dht_pin = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
photoresistor_pin = machine.ADC(26)

# Create DHT11 sensor instance
dht_sensor = dht.DHT11(dht_pin)

# Function to read sensor data
def read_sensor_data():
    dht_sensor.measure()
    temperature = dht_sensor.temperature()
    humidity = dht_sensor.humidity()
    light_value = photoresistor_pin.read_u16()
    return temperature, humidity, light_value

# Function to send data to Ubidots
def send_data_to_ubidots(temperature, humidity, light_value):
    url = "https://industrial.api.ubidots.com/api/v1.6/devices/picowboard/?token=BBFF-rEG0PLVVDV6p67X3ZRyMtDl8hJPVrR"
    payload = {
        "temperature": temperature,
        "humidity": humidity,
        "light_intensity": light_value
    }
    response = urequests.post(url, json=payload)
    print("Data sent to Ubidots. Response:", response.text)

# Main loop
while True:
    temperature, humidity, light_value = read_sensor_data()
    print("Temperature:", temperature, "°C")
    print("Humidity:", humidity, "%")
    print("Light Intensity:", light_value)
    send_data_to_ubidots(temperature, humidity, light_value)
    utime.sleep(60)  # Delay for 60 seconds

```


---
## Transmitting the data / connectivity
The data in this project is transmitted to the internet using the Wi-Fi protocol. The code establishes a Wi-Fi connection to the local network, as described earlier, and then sends the data to Ubidots, a cloud-based platform for IoT applications.
The data is sent to Ubidots at regular intervals determined by the utime.sleep() function in the code. In the provided code, the data is sent every 60 seconds (utime.sleep(60)). You can adjust this interval based on your specific requirements and the frequency at which you want to monitor and update the sensor data.
The data is sent to Ubidots at regular intervals determined by the utime.sleep() function in the code. In the provided code, the data is sent every 60 seconds (utime.sleep(60)). You can adjust this interval based on your specific requirements and the frequency at which you want to monitor and update the sensor data.


---

## Presenting the data
The presentation part of the project involves creating a dashboard on the Ubidots platform to visualize the sensor data and provide meaningful representations. The dashboard includes specific widgets that enhance the understanding of the data.

For the temperature, a thermostat symbol widget was selected to display the temperature value in both written form and as a visual representation. Additionally, the widget shows the time of the last update, providing real-time information about the temperature in the bedroom.

![](https://hackmd.io/_uploads/S1977mlF3.png)

To represent the Relative humidity, a water tank symbol widget was chosen. This widget visually represents the humidity level, and it includes the last measured value displayed in written form. This representation helps in quickly assessing the humidity level and monitoring any changes.

![](https://hackmd.io/_uploads/rJat7meF2.png)


For the light intensity, an Indicator widget was used. This widget provides a visual indication of the light intensity level in the bedroom.

![](https://hackmd.io/_uploads/BkMoXQlYh.png)


The data is stored in the Ubidots database and can be preserved for a configurable duration. By default, Ubidots retains the data for 30 days, but you can adjust this based on your preferences and analysis requirements. Storing the data allows for historical analysis, trend identification, and comparison over time.

Here is an example visual representation of the dashboard:

![](https://hackmd.io/_uploads/B1twSXxK3.png)

The data is saved at regular intervals based on the frequency of data transmission from the Raspberry Pi Pico W. In the provided code, the data is sent every 60 seconds. This ensures that the dashboard reflects near real-time updates and provides an accurate representation of the current sensor readings. Regularly saving the data allows for continuous monitoring, analysis, and decision-making to improve the bedroom environment and ensure optimal comfort for better sleep quality.

---
## Finalizing the design

![](https://hackmd.io/_uploads/rJQTTmxYn.jpg)


The project has been successfully completed, resulting in a functional system that monitors and displays the temperature, humidity, and light intensity in the bedroom. The Raspberry Pi Pico W, along with the connected sensors, effectively collects the data, which is then transmitted to the Ubidots platform. The Ubidots dashboard presents the data in a visually appealing manner.

The final design includes a thermostat symbol for temperature, a water tank symbol for humidity, and an indicator widget for light intensity. These visual representations are accompanied by written values and timestamps, providing a comprehensive understanding of the environmental conditions.

Overall, the project has met its objectives and provides valuable insights into the bedroom environment. Future improvements could involve advanced data analysis techniques, user interaction elements, integration with smart devices, and design optimization.
