# EcoCool: Energy-Saving Night Ventilation ###### tags: `night flushing` `night purging` `energy efficiency` `tutorials` `night cooling` `Wifi` This tutorial is inspired by an assignment from the Summer 2024 course "Introduction to Applied IoT." This project is a proof of concept for a night cooling system, using cooler night air to reduce heat that has built up during a hot summer day in buildings. This saves energy and can reduce or even eliminate the need for air conditioning in regions where the night temperature drops considerably. To achieve this, we need some data: indoor and outdoor temperature, weather forecast (next day's max temperature) and some way of checking if we are venting the apartment/house. ## Time estimation for the project: Roughly 6 to 8 hours depending on prior knowledge and account settings (you will need to start accounts on some services if you don't already have them). #### The complete code can be found here: <a href= https://github.com/hkenshin21/Night_Flush_IoT_Project> my Github</a> --------- | kl223ph | Summer 2024 ## Objective My objective is to solve an increasing problem in homes and dwellings due to more extreme weather. Night flushing is underutilized in Sweden despite its effectiveness, and it can mitigate the need for air conditioning by improving nighttime ventilation in buildings designed primarily for heat retention rather than cooling. I live in an apartment, therefore my proof of concept will be adapted to what's within my control (open or close the windows to ventilate my apartment). The project can be modified for use in homes, offices, schools, etc. It whould involve automation that adjusts the ventilation system to optimize airflow day and night based on weather forecasts and desired indoor temperatures. I chose this project because it aligns with my line of work and my deep interest in energy efficiency and smart systems. ### Some insights I am hoping to get from the collected data: * Learn my homes thermal insulation capabitilies (learn how long time does it take until thermical balance). * I'm measuring humidity along with temperature, I want to learn how humidity affects the perceived temperature. * How accurate is the forecast? if it consistently differs because of local factors (balcony with glas, trees around, buildings around creating a microclimatic environment) - and what do I need to adjust? I do forecast a lot of testing and adjusting. ## Material I got some of the materials for my project from the kits available for the course: * <a href= https://www.electrokit.com/lnu-starter.>StartKit ~35 EUR</a> * <a href= https://www.electrokit.com/sensor-kit-25-moduler>25 Sensor Kit ~ 27 EUR</a> I'm using the cables from the kits, these are not listed in the component list below (so add a couple of EUR to the final sum for these if you don't already have them): | Materials| Ammount | Price (EUR) | Total (EUR)| Link | | ---------| ------- | ---------- | ----------- |----------- | | Raspberry Pi Pico WH| 3 | 9.7 | 29.1 |<a href= https://www.electrokit.com/raspberry-pi-pico-wh>RP2040</a>| | Micro USB to USB cable (4 pins)| 3 | 3 | 9|<a href=https://www.electrokit.com/micro-usb-till-usb-hona-adapter><Micro USB to USB (4 pins)></a> | | DHT11 Temperature and Humidity Sensor| 2 | 4.5 | 9 |<a href= https://www.electrokit.com/digital-temperatur-och-fuktsensor-dht11>DHT11</a>| | Digital Hall Sensor | 1 | 3.5 | 3.5 |<a href=https://www.electrokit.com/halleffektsensor-digital>Hall Sensor</a> | | Magnet Neo35 Ø5mm x 5mm | 1| 1| 1|<a href=https://www.electrokit.com/magnet-neo35-5mm-x-5mm>Magnet 5mm</a>| | Two color LED module (optional)| 1| 1.7 | 1.7|<a href=https://www.electrokit.com/led-modul-rod/gron-3mm >Two color LED module</a>| | Breadboard large 840| 1| 6 | 12|<a href=->Breadboard 840</a>| | Breadboard medium (400) | 2| 4.3| 8.6|<a href=https://www.electrokit.com/kopplingsdack-400-anslutningar>Breadboard 400</a>| | | |TOTAL| 74|| #### Raspberry Pi Pico WH (RP2040): ![pico](https://hackmd.io/_uploads/S1bn1Fp80.jpg) The Raspberry Pi Pico W or also known as RP2040 is a small, powerful microcontroller board with the RP2040 chip. It includes built-in Wi-Fi and Bluetooth for easy wireless communication. Its compact size makes it perfect for IoT projects, robotics, and other electronics. You can program it in MicroPython, C, and other languages, making it suitable for both beginners and advanced users. The Pico W is a cost-effective and versatile option for various projects. _If you want to know more about this little device, here is an awesome guide: <a href=https://lnu.app.box.com/s/jjj9j99c4kn0r7xst65rkgq64jbp6p19 >The official raspberry pi pico guide</a>_ #### DHT11: ![DHT11](https://hackmd.io/_uploads/HJBPyt6UA.jpg) The <a href = "https://www.electrokit.com/upload/product/41015/41015728/DHT11.pdf" >DHT11</a> is an affordable digital sensor for temperature and humidity, measuring 0-50°C and 20-80% humidity with ±2°C accuracy and a repeatability of ±1°C (repeatability is the ability of the sensor to provide consistent readings when measuring the same temperature multiple times under the same conditions). It uses a single-wire digital interface, has low power consumption, and is commonly used in weather stations, HVAC systems, and home automation. For the purposes of this project it's "good enough". #### 3144EUA-S Sensitive Hall-Effect Switch: ![hall](https://hackmd.io/_uploads/rk13IspLR.png) The 3144EUA-S is a sensitive Hall-effect switch sensor that detects magnetic fields and outputs a digital signal. Known for its high sensitivity, reliability, and low power consumption, it's commonly used in automotive, industrial, and consumer electronics. I am using it to detect if a window is open or closed (by using a magnet). #### Two-Color LED Module (optional): ![LED](https://hackmd.io/_uploads/B1ic8ia8A.jpg) The two-color LED module emits red and green light. You can adjust the brightness of each color using PWM (Pulse Width Modulation), allowing for a range of color combinations. This module is easy to integrate into various projects and is commonly used for indicators, displays, and decorative lighting. ## Computer setup I use Windows 10 and chose Visual Studio Code since I already had it for web design projects. Working with MicroPython is slightly different from Python because you need to run programs on the microcontroller itself. However if you want a more beginner friendly IDE you could try <a href = "https://hackmd.io/@lnu-iot/SyTPrHwh" >Thonny</a> VS Code is a free, open-source code editor developed by Microsoft. It supports multiple programming languages and offers features like debugging, syntax highlighting, and version control. #### Getting started with the IDE: * Start by installing Node.js LTS: <a href = https://nodejs.org/en/ >Download Node.js LTS here</a>. * Install VS Code: <a href = https://code.visualstudio.com/Download > Download Visual Studio Code </a> * Open VS Code and look for Pymakr in the extensions manager (left panel icon or from view -> Extensions) A more detailed guide that also offers instructions on how to do this on different OS can be found here: <a href= https://hackmd.io/@lnu-iot/rkiTJj8O9 >Installing VS Code IDE</a> #### Raspberry pi-pico-wh (RP2040) Make sure you get the right microcontroller, there are several Raspberry Pi sorts. The WH stands for W: Wireless, indicating Wi-Fi connectivity, H: Headers, indicating pre-soldered header pins (which may not be needed if you intend to solder your project). The first thing you need to do is update the Firmware on Raspberry Pi Pico W and then do a simple test to make sure everything works properly. For this you need an USB cable that can transfer data (USB cable with four pins). ##### Updating the firmware on your new device * If you got the RP2040 with headers, remove the sponge before proceeding and place it on a breadboard (be careful with the pins as they can be quite sharp). * Download the latest micropython firmware (uf2 file) from this <a href = https://micropython.org/download/RPI_PICO_W/>website</a> * Connect the micro-usb into the RP2040 (be sure to hold it firmly to avoid bending it). * While holding the BOOTSEL button, connect it to your computer's USB-port, once connected release the BOOTSEL button. This makes the RP2040 go into USB-storage mode and you will be able to see it as a new drive named RPI-RP2. * Copy-paste the uf2 to the storage. * Your RP2040 will automatically disconnect from your computer (the drive will disappear) * Unplug and plug again. * Test your microcontroller with a simple code, in <a href = https://github.com/iot-lnu/pico-w/tree/main > this repository </a> you will find lots of code snippets for sensors used with RP2040. Why not try the first project in the list <a href= https://github.com/iot-lnu/pico-w/blob/main/sensor-examples/P1_HelloWorld> "P1_HelloWorld" </a> or test the Raspberry Pi Pico onboard LED with <a href = https://github.com/iot-lnu/pico-w/blob/main/sensor-examples/P2_Blink >"P2_Blink"</a>. ![bootsel](https://hackmd.io/_uploads/SkHmzw2UC.png) Now you are ready for wiring and programming! If you need a more detailed explaining, follow this tutorial: <a href = https://hackmd.io/@lnu-iot/rkFw7gao_>Update Firmware and test Raspberry Pi Pico W </a> ##### Uploading the code from Github to your (RP2040) If you are not familiar with VS Code and/or its PyMark extension or if you went for Thonny IDE I can recommend this guide: <a href = https://hackmd.io/@lnu-iot/B1T1_KM83> Therminology and project structure</a> ## Putting everything together Here is a summary of the electronic components used in this project and how they interact with each other. The circuit diagram in several formats and code can be found on my <a href = https://github.com/hkenshin21/Night_Flush_IoT_Project>Github. </a> I use three Raspberry Pi Pico WH + breadboards, all are connected to power dapter (could also be run with batteries). ### Outdoor sensors: * Rapberry Pi Pico WH + DHT11 Temperature and Humidity Sensor * Monitors outdoor temperature and humidity. * Sends data at decided intervals. ![DHT11Fritz](https://hackmd.io/_uploads/S1VN5A6I0.png) ### Window sensor: * Rapberry Pi Pico WH + Hall-Effect Switch + magnet * Monitors the status of the window open/close * Sends data when status changes. ![HallSensorFritz](https://hackmd.io/_uploads/Hkq6c0TUA.png) ### Indoor pico (master): * Rapberry Pi Pico WH + DHT11 Temperature and Humidity Sensor * Monitors indoor temperature and humidity. * Sends data at decided intervals, receives data from the other sensors and manages the logic. * Red-green LED gives signals based on received data (optional) ![masterFritz](https://hackmd.io/_uploads/S1kSLk0LR.png) ### Energy consumption All the components I am using are mounted on PCBs (Printed Circuit Boards) which have in-built resistors. But if you need to use resistors you can check <a href = https://github.com/iot-lnu/pico-w/tree/main > this repository</a>. For power calculations I used information from this site:<a href = "https://peppe8o.com/raspberry-pi-pico-w-power-consumption/">Raspberry pi pico w power consumption</a>. I did some asumptions on energy mode, so as not to err on the lower side I use the Wifi with power saving disabled. So in reality it is probably lower. I got around 9,5 kWh/year which at 1,5 SEK/kWh = 14,25 SEK (roughly 1,25 EUR). ![PowerCalculations](https://hackmd.io/_uploads/rkevnhCU0.jpg) I did some research on WiFi and LoRa and found an interesting paper which I comment on here (see link and comment on the Wifi icon): <a href = "https://github.com/hkenshin21/Night_Flush_IoT_Project/blob/main/images/Night%20Flush%20Project%20System%20architecture%20diagram2.pdf"> Night Flush System architecture diagram (PDF)</a> ## Platforms ### Adafruit I chose to use a free subscription to <a href = "https://io.adafruit.com/" >Adafruit IO</a> and run <a href = "https://nodered.org/" > Node-RED </a> locally in my pc: Data is sent to Adafruit via MQTT. All devices and Node-RED send data to Adafruit, with the master device and Node-RED subscribing to certain feeds. The resulting message is sent via webhook to my Discord server. I chose Adafruit IO for its beginner-friendly interface, supporting up to 10 data feeds, 5 dashboards, and 30 days of data storage in its free version. Minimal coding is required for setup, and it supports webhooks for real-time notifications. ### NodeRED (runned in Docker) For weather forecast data in my project, I chose Node-RED, a tool simplifying automation workflows with its visual editor. You create flows by dragging and dropping nodes, each representing tasks like data collection or web service connections. To ensure continuous operation, I use <a href = "https://www.docker.com/">Docker </a> on my PC, facilitating potential future migration to a Raspberry Pi for server-like functionality. It ensures an app runs consistently across different computers, avoiding software or setting issues. If you want to learn more about Docker, check out this <a href = "https://www.youtube.com/watch?v=rOTqprHv1YE&t=777s" > video on youtube. </a> In the future, scaling may involve migrating Node-RED to a cloud server with a paid subscription. This could accommodate storing data from multiple feeds or extending storage duration using services like Adafruit or InfluxDB. ## The code The code is extensive, so I'll explain each part and core functions. For detailed comments and the complete code use <a href= https://github.com/hkenshin21/Night_Flush_IoT_Project>my Github </a> . Follow steps 1 and 2, then use the code from GitHub. 1. You'll need external libraries, available in my repository. See README.md for their sources. 2. In GitHub, there are 3 maps, each containing code for an RP2040. If you connect sensors to the same pins I used, replace credentials in each `keys.py` file (one per RP2040) with your own. ```Python #Your WiFi Credentials WIFI_SSID = 'Your_wifi_SSID' WIFI_PASS = 'Your_wifi_Password' # For Adafruit IO (AIO) configuration: AIO_SERVER = "io.adafruit.com" AIO_PORT = 1883 AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # Can be anything AIO_USER = "your_user_name_here" AIO_KEY = "your_aio_key_here" AIO_IN_TEMP_FEED = "your_feed_MQTT" ``` All 3 `main.py` files use more or less the same code for conecting and sending data: #### `in main.py` ```Python #Example of code for sending data: def send_data(tempFeed, tempData, humFeed, humData): # Function to publish to Adafruit IO MQTT server at a fixed interval (300000 ms = 300 seconds = 5 minutes) # Uses time.ticks_ms to check how long time it's been since last sent feed def connectAndSend(): # Try WiFi Connection # Uses the MQTT protocol to connect to Adafruit IO # Repeat this loop forever: getReadings() send_data(feed, data) #sends the data to the chosen feed adress client.check_msg() #checks for messages (if subscribing) finally: # If an exception is thrown ... # ... disconnect the client and clean up. connectAndSend() ``` ### Outdoor sensor #### `main.py` Connects to internet (WiFi) Enters a loop that reads and sends data every 5 minutes to Adafruit. ```Python def getReadings() #Gets the readings for the sensors #returns two variables: temperature and humidity connectAndSend() #explained above ``` ### Window sensor #### `main.py` Connects only when sending a feed on the windows status (open or close) ```Python def checkWindow(): # True for open, False for closed. def checkStatusSendOnChange(): #loops and checks for changes in status #connect and send new status. #disconnet ``` ### Indoor pico (master) Connects to internet Susbcribe to feeds (outdoor temperature, weather forecast, window status) Measure indoor temperature and humidity and send data to Adafruit Checks for new messages (subscribed data) Runs night flush logic and sends a message if the status has changed #### `main.py` This code manages the connection to WiFi and the Adafruit IO MQTT server, reads temperature and humidity data from a DHT11 sensor, and controls window status for night cooling. It saves and loads forecast and window status data to ensure persistence across reboots, and it uses PWM to control an RGB LED for status indication. ```Python # relevant imports... """Saving variables to RP2040 memory""" def on_message(topic, msg): decoded_string = msg.decode('utf-8') forecast = float(decoded_string) saveForecast(forecast) # Save the variable to memory """Runs a code from nightFlushLogic.py (described in next part) Checks for a new msg, sends it by MQTT if so:""" def checkActionMsg(): global actionMsg oldMsg = actionMsg newMsg = nightFlushLogic.actionMessage(windowIsOpen, forecast,latestInTemp,latestOutTemp) if oldMsg != newMsg: actionMsg = newMsg return newMsg return "" connectAndSend() #Described earlier ``` #### `NightFlushLogic.py` This code manages the logic for the night cooling system, it calculates the desired indoor temperature, checks if a night flush (cooling by opening windows) is necessary, and returns action messages to open or close windows accordingly. ```Python def calculateSetPoint(forecast) # Calculate setpoint temperature based on forecast, returns a float. """ These determine the settings based on hot or cold forcasts. checkNightFlush() returns a boolean: window open (True) or closed (False) """ def hotDaySetting(deltaInSet, deltaInOut) def coolDaySetting(deltaInSet, deltaInOut) def checkIsHotDay(forecast) def checkNightFlush(forecast, tempIn, tempOut) """ actionMessage() is called by main.py this results in a message that is sent to Adafruit indicating what should be done or informing on the status""" def actionMessage(windowIsOpen, forecast, tempIn, tempOut): calculateSetPoint(forecast) nightFlush = checkNightFlush(forecast, tempIn, tempOut) if not windowIsOpen and nightFlush: msg = "Open the windows" elif windowIsOpen and nightFlush: msg = "Airing ON (window is open)" elif windowIsOpen and not nightFlush: msg = "Close the windows" else: msg = "Airing OFF (window is closed)" return msg ``` ### Settings in Node-RED and Adafruit In Node-RED an HTTP-request node fetches JSON data from the <a href="https://opendata.smhi.se/apidocs/metfcst/index.html" > SMHI Open Data - API </a>. then a function node extracts the highest temperature and sends it to Adafruit via MQTT-protocol. A function node then extracts the highest temperature and sends it to Adafruit via MQTT. This process runs three times a day: at 6 pm for the next day, and twice during the night for the current day. Node-RED uses JavaScript for its functions. The JS code for extracting the highest temperature is available on my GitHub: <a href = "https://github.com/hkenshin21/Night_Flush_IoT_Project/tree/main/NodeRed" >JavaScript for NodeRed</a>. If you use a different site to fetch data, you may need to modify the script. I recommend providing ChatGPT with a sample of the JSON data to generate the necessary JS code. With minor modifications, this can often give you a good starting point. ![NodeRed](https://hackmd.io/_uploads/S1EJR3RUR.png) For getting started with Adafruit I followed this tutorial: <a href = "https://hackmd.io/@lnu-iot/r1yEtcs55" > Adafruit IO </a> it is pretty straightforward. See the diagram in the next section for a better understanding of what is sent where. ## Transmitting the data / connectivity Data is sent to internet via Wi-Fi using MQTT. Here is a visual representation of the system architecture: ![SystemArchitecture](https://hackmd.io/_uploads/BkqVypA80.png) Here you can access the same picture with active links and notes covering formats, system choices and future ideas: <a href = "https://lucid.app/lucidspark/fa67dbe1-1eb0-43e4-aeaf-2969a3c2fb69/edit?invitationId=inv_9a52003f-a0c1-4b2f-a23b-10db9add7999&page=0_0#"> Night Flush System architecture diagram (Lucid Spark) </a> <a href = "https://github.com/hkenshin21/Night_Flush_IoT_Project/blob/main/images/Night%20Flush%20Project%20System%20architecture%20diagram2.pdf"> Night Flush System architecture diagram (PDF)</a> ## Presenting the data I chose <a href = "https://io.adafruit.com/h_kenshin21/dashboards/in-out-temperature">Adafruit dashboard </a> because it was easy to set up and works well. It includes gauges, a message block for the latest feed (temperature, humidity, forecast), a toggle button for window status, and a graph and log for historical indoor and outdoor temperature data. Data is stored for 30 days which is enough in this project. ![Dashboard](https://hackmd.io/_uploads/B1U6HhpLR.png) Adafruit is an OK option, I need to refresh the page sometimes to get the latest readings so I am considering testing other options. Probably Node-RED with Influx db. I'm using a webhook to get a message on Discord prompting when to open or close the window. However, since it only allows messages every 15 minutes, I will likely change this. ## Finalizing the design Here are some pictures of the sensors and comments on the set up. I've made budget RP2040 cases for protection. Overall, I'm pleased with the results and will definitely continue tweaking and testing other settings. I have learn a lot more than I expected, it has been a really fun course to take. <a href = "https://youtu.be/jSCFRoGST6Y">Demo on youtube</a> ### Outdoor sensors: I placed the outdoor temperature sensor in a ventilated, shaded spot inside a glazed balcony. The readings depend on whether the balcony's glass panes are open or closed, which is relevant since the window used for night cooling faces the balcony. The sensor is positioned about 60 cm above the floor. ![balkong](https://hackmd.io/_uploads/rkrbERT8C.jpg) \* The two 7 Segment LED Display in the picture are for future use :) ### Window sensor: The window sensor is placed on the edge of the window frame. When the window is closed, the sensor is close to a magnet, causing the sensor's built-in LED to light up. When the window is opened, the magnet moves out of range, and the LED turns off. ![open_closed](https://hackmd.io/_uploads/HJcmkqaL0.jpg) #### DIY budget case for Raspberry pi pico I'm actually pretty proud of the results :) what do you think? - only 13 SEK = ~ 1.1 EUR and it comes in different colors! ![Normal_budget_pico_case](https://hackmd.io/_uploads/rJjpkcpL0.jpg) *Other uses for a solderer... ### Indoor pico (master) The indoor Raspberry Pi Pico, measures indoor temperature and humidity and integrates all data to send messages based on the previously described logic. The sensor is placed where the temperature remains consistent, unaffected by brief window openings. It is located centrally in the apartment, at a height of 1.5 meters. ![master](https://hackmd.io/_uploads/BJIjb5aUR.jpg) I made a *bumpy roadmap* describing my first idea, bumps on the road and decisions from start to final project: <a href= "https://lucid.app/lucidspark/5aae9dcd-8fcb-43dc-a3ca-a60e27e8f812/edit?viewport_loc=352%2C1922%2C6064%2C3054%2C0_0&invitationId=inv_bbc60149-4113-4f1a-a15c-fc9ad01a08f4">My IoT roadmap (Lucid Spark)</a>, <a href = "https://github.com/hkenshin21/Night_Flush_IoT_Project/blob/main/images/MY%20roadmap.pdf">My IoT roadmap(pdf)</a>. ## Some Ideas for the future: * Integrate wind speed sensors to understand their impact on heat exchange in my home. * Implement logic, such as a PID regulator, to maintain stable temperatures. * Experiment with settings to optimize energy efficiency for microcontrollers. * Develop a working prototype for multiresidential buildings. ## Images from testing: Message prompt to open the window. Next day will be hot and current outdoor temp is lower. The prompt is sent by Webhook to my discord channel: ![WCloseNFOpen](https://hackmd.io/_uploads/HJCCi6CIA.jpg) Opening the windows sends a msg: "Airing ON" ![WOpenNFOpen](https://hackmd.io/_uploads/rJdwh6ALR.jpg) In a scenario when next day is cold if the the window is open, I get a prompt to close it. ![WOpenNFClose](https://hackmd.io/_uploads/ByhY3TRI0.jpg) If I then close the window, I get a notification confirming this. ![WCloseNFClose](https://hackmd.io/_uploads/Sy2cna0IR.jpg) Finally, if the next day is going to be a cold day but the inside temperature is too high, it will still prompt me to open the windows. I didn't get a discord notification because I did the test before the 15 minute limit had passed. With this I wanted also to show that for notifications that may come often, another option should be considered. ![colddayOnFlush](https://hackmd.io/_uploads/B1eil0CUR.png)