---
# System prepended metadata

title: Automated and over-Wifi Controller for Air Conditioner
tags: [IOT]

---

**Final Report**
**Automated and over-Wifi Controller for Air Conditioner**


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


Abdul Rahman Charfou (ac223ep)

# **Short description** 
The concept involves transforming a conventional air conditioning unit into a smart device that intelligently adapts its operation according to the surrounding conditions. By integrating innovative technology, this air conditioning system will be able to monitor, learn, and react to changes in its environment, enhancing both comfort and energy efficiency. Moreover, the upgraded system would also have the capability to be controlled remotely via the internet. 
This opens up a world of convenience, allowing users to manage their home or office temperatures from virtually anywhere, ensuring the perfect environment awaits them upon arrival.

**Amount of time**
Estimated 30 Hours

# **Objective**
The primary motivation behind selecting this project stems from my personal experience of enduring uncomfortably warm summers. A regular air conditioning unit, when left on for extended periods, tends to be inefficient and consumes a considerable amount of electricity. Therefore, introducing an intelligent system that maintains the preferred temperature without constant manual adjustment would drastically increase efficiency. Furthermore, this project would offer the added advantage of remotely monitoring and controlling the home's temperature when outside, such as while travelling.

The objective of this initiative is to provide a more sustainable alternative for the conditional use of air conditioners, improving not just the energy efficiency but also consumer convenience and comfort. By reimagining the way air conditioners function, the aim is to deliver better value to consumers, providing them with a high level of comfort without the need for continuous intervention or excessive energy use.

In terms of broader implications, this project could shed light on how to make the use of air conditioners more efficient and sustainable, delivering more value at less cost. The innovative design for conditional air conditioners that this project proposes could pave the way for a new generation of smart, energy-efficient appliances, and redefine how we manage and control our living spaces.

================================================================


# **List of Material**
![](https://hackmd.io/_uploads/HyR5vZsdn.png)

**RP PICO W:** A compact microcontroller board capable of Wi-Fi connectivity. In the project, it serves as the central hub that connects and orchestrates the operation of all the sensors and components, making them work in unison. 

![](https://hackmd.io/_uploads/SkW0w-iu3.png)

**DHT11 Sensor:** A low-cost temperature and humidity sensor. In this context, it's used to continuously monitor the temperature and humidity inside the room where the air conditioner is installed, providing valuable data for adaptive control.

![](https://hackmd.io/_uploads/Sy3lu-o_n.png)

**IR Receiver:** An electronic device that receives infrared signals. Its role in this project is to capture the signals from the Air Conditioner's remote controller, essentially learning the "language" of the AC unit.

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

**IR Transmitter:** A device that emits infrared signals. In our setup, it will transmit the recorded signal to the air conditioner, adapting its commands based on the room's temperature and humidity or based on the user's preferences, which can be set remotely via Wi-Fi.

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

**RGB Light:** A color model used in LED lighting systems. In this case, the RGB light is used to provide a visual representation of the room's temperature and humidity levels. For instance, it might show red when it's too warm, green when conditions are moderate, and blue when it's too cold.

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

**Micro-USB:** A miniature USB connector used for power supply and data transfer. It powers the RP PICO W and facilitates bidirectional data transfer.

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

**Breadboard:** A tool used for creating and testing electronic circuits without soldering. It's used in this project for easy setup and modification of circuits, enabling quick iterations during the prototyping stage.

**Pricing and where to buy from**
All the materials used were bought from [ElectroKit](https://electrokit.com). 
Included in [StartKit](https://www.electrokit.com/produkt/start-kit-applied-iot-at-linnaeus-university-2023/) for 399SEK or as listed below if seperate:

| Material     | Price  | Store                                                                       |
| ------------ | ------ | --------------------------------------------------------------------------- |
|1x RP Pico W    | 98 SEK | https://www.electrokit.com/produkt/raspberry-pi-pico-w/                     |
| 1xDHT11 Sensor | 49 SEK | https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/ |
| 1xMicro-USB    | 39 SEK | https://www.electrokit.com/produkt/usb-kabel-a-hane-micro-b-5p-hane-1m/     |
|  1x(40xWiring cables 30cm M-to-F)             |   49 SEK     |                                                                         https://www.electrokit.com/produkt/labbsladd-40-pin-30cm-hona-hane/    |
| 1xBreadboard  840 connections   | 69 SEK | https://www.electrokit.com/produkt/kopplingsdack-840-anslutningar/          |

Included in the [Sensor Kit](https://www.electrokit.com/produkt/sensor-kit-25-moduler/) for 299SEK or as listed below if seperate:


| Material       | Price |  Store   |
| -------------- | ----- | --- |
| 1xIR Receiver    |    32 SEK   |   https://www.electrokit.com/produkt/ir-sensor-38khz-skarmad/  |
| 1xIR Transmitter |    26  SEK   |   https://www.electrokit.com/produkt/ir-sandare-38khz/  |
| 1xRGB Light      |  19 SEK     |    https://www.electrokit.com/produkt/led-modul-rgb-smd/ |



================================================================

# **Computer Setup**

For the setup, the RP Pico W was interfaced with the computer using a micro-USB cable. Rather than using the [Thonny IDE](https://thonny.org/) and [Node.js](https://nodejs.org/en) plugin, a specific firmware named "pico-w-anvil-v0.1.2-complete.uf2", available at https://github.com/anvil-works/anvil-pico/releases, was utilized to flash the RP Pico W. This firmware allows the RP Pico W to run MicroPython, leveraging its simplicity and power. The computer served not just as the programming interface but was also used to monitor the data measured by the RP Pico W. However, the Wi-Fi connectivity of the RP Pico W enables data monitoring from any device equipped with a web browser and Wi-Fi access. This flexible setup ensures efficient development, seamless programming, and remote monitoring of the air conditioning system.

**Chosen Firmware:** For this project, the specific firmware "pico-w-anvil-v0.1.2-complete.uf2" was used. This firmware is designed to interface the RP Pico W with the [Anvil](https://anvil.works/) platform, providing easy integration with web-based applications. This firmware can be found and downloaded from the [Anvil GitHub repository](https://github.com/anvil-works/anvil-pico/releases).

**Code Structure and Upload Process:** The programming of the RP Pico W was organized into two primary Python scripts: boot.py and main.py. The boot.py script holds the code for connecting the RP Pico W to the Wi-Fi network. On the other hand, the main.py script is where the RP Pico W is linked to the Anvil web application.

Both of these scripts are uploaded directly to the boot folder of the RP Pico W. This setup ensures that, upon powering the device, it immediately establishes Wi-Fi connectivity and initiates interaction with the Anvil web application. This way, the device promptly starts driving the sensors and making decisions based on the gathered data.

**Web Application Interaction:** With Anvil, I designed a web application that features buttons capable of triggering functions on the RP Pico W. It also has visualizations of data measured by the DHT11 sensor. This interface not only allows remote control of the air conditioning system but also provides an intuitive way to monitor the system's performance and data in real-time.

**RP PICO Pinout Mounted on Breadboard**
![](https://hackmd.io/_uploads/HJ4JUkod2.png)

================================================================


# **Putting Everything Together**

**RP Pico W**: Mounted on the breadboard, the RP Pico W is the central unit of this setup. It's powered and connected to the computer via a Micro-USB cable for programming and data transfer. On the breadboard, wiring from pin 38 (GND, Ground) is connected to the blue vertical line (ground line), and wiring from pin 36 (3V3 OUT, 3.3 Volt Output) is connected to the red vertical line (power line). This arrangement allows multiple sensors to be powered using only two pinouts from the RP Pico W.

**DHT11 Sensor:** This sensor monitors temperature and humidity. It's powered by connecting the ground (-) pin to the blue line on the breadboard (ground), and the VCC (voltage supply) pin to the red line on the breadboard (3.3V power). For data transmission, the signal (S) pin is connected to pin 22 (GP17) on the RP Pico W.

**IR Receiver:** The IR receiver is connected in a similar way as the DHT11 sensor, with the ground and Vcc pins connected to the blue and red lines on the breadboard, respectively. The signal (S) pin on the IR Receiver is connected to pin 21 (GP16) on the RP Pico W.

**IR Transmitter (NEC Protocol)):** The ground (GND) pin is connected to the blue line on the breadboard (ground). However, unlike the other components, the IR transmitter's Vcc pin is connected to pin 40 (VBUS) on the RP Pico W, which supplies 5V instead of 3.3V, to enhance the strength of the IR signal transmitted to the air conditioner. The signal (S) pin of the IR Transmitter is connected to pin 24 (GP18) on the RP Pico W.

**RGB Light:** The RGB light has four pins - ground (GND), Red (R), Green (G), and Blue (B). The GND pin is connected to the blue line on the breadboard (ground), while the R, G, and B pins are connected to pin 34 (GP28), pin 32 (GP27), and pin 31 (GP26) on the RP Pico W respectively.

In terms of resistors, current, and voltage, each component is designed to work with 3.3V or 5V. It's crucial to ensure each component is connected correctly, following the layout and guidelines above, to prevent any electrical shorts or potential damage.

While the current setup on the breadboard is primarily for development and prototyping, it can indeed be used as a production model with slight modifications to secure the connections better. The breadboard allows for easy modifications, and once the final design is locked down, a more permanent solution like a Printed Circuit Board (PCB) or soldering the connections can be implemented.

All the wirings to the sensors are shown in the **Circuit Diagram** below:
![](https://hackmd.io/_uploads/HJH22kod2.png)



================================================================

# **Platform**

The platform I've chosen for visualizing the data is [Anvil](https://anvil.works), an accessible, easy-to-use web app framework. This platform was particularly appealing due to its simplicity, the ability to build full-stack web applications with just Python, and its built-in functionality for data analysis and visualization. It offers an ideal mix of user-friendly features and flexibility, making it a great tool for my project.

Before I decided on Anvil, I explored other platforms, such as Ubidots and Node-RED. Despite their robustness, I found these platforms to have a steeper learning curve and they felt more complex compared to Anvil. The straightforward interface of Anvil, along with the ability to code both front-end and back-end in Python, made it my preferred choice.

For the current scope of the project, Anvil's online platform is used, which offers easy deployment and accessibility. This setup is not only user-friendly but also secure. However, I acknowledge that a self-hosted setup could provide additional benefits, like full control over the server environment.

In terms of cost, the goal of this project is to demonstrate that an efficient, smart air conditioning solution can be achieved without incurring hefty expenses. I intend to use free tools and services as much as possible. Anvil’s free tier offers a wide range of capabilities sufficient for this project. However, I'm open to considering minimal investments if they significantly enhance the project’s value.

When considering potential alternatives and expansions for the project, numerous ideas have crossed my mind. But, to prevent the project from becoming too sprawling and complex, I'm sticking to the original plan for now. The current setup provides room for additional features and improvements in the future. The primary focus at this stage is to ensure that the core functionality is reliable and efficient before adding more complexity. The future holds endless possibilities for this project, and I eagerly anticipate exploring them further once the course is completed.

================================================================

# **The Code:**
Alongside lecture materials and online tutorials, ChatGPT was utilised to create the Codes as well as check for errors, then it was my responsibility to assure everything was working as planned.

**boot.py**
```=python
#############################################
# Provide your Wifi connection details here #
#############################################

WIFI_SSID = "XXXXX"
WIFI_PASSWORD = "XXXXX"

#############################################

import network
from time import sleep
from machine import Pin
import ntptime

sleep(1) # Without this, the USB handshake seems to break this script and then fail sometimes.

led = Pin("LED", Pin.OUT, value=1)

wlan = None
while not wlan or wlan.status() != 3:
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASSWORD)

    # Blink LED slowly until the Wifi is connected.

    while True:
        print(wlan)
        led.toggle()
        sleep(0.2)
        if wlan.status() in [-1, -2, 3]:
            break

# Set the RTC to the current time

ntptime.settime()

# Solid LED means we're connected and ready to go
led.on()
print(wlan)



```

**main.py**
```python
import anvil.pico
import uasyncio as a
from machine import Pin

# This is an example Anvil Uplink script for the Pico W.
# See https://anvil.works/pico for more information

UPLINK_KEY = "server_UFSXDXGXICZX7XZ3WJ2TBMS-RAWITHGMMN5JG6AJ"

# We use the LED to indicate server calls and responses.
led = Pin("LED", Pin.OUT, value=1)


# Call this function from your Anvil app:
#
#    anvil.server.call('pico_fn', 43)
#

@anvil.pico.callable(is_async=True)
async def pico_fn(n):
    # Output will go to the Pico W serial port
    print(f"Called local function with argument: {n}")

    # Blink the LED and then double the argument and return it.
    for i in range(10):
        led.toggle()
        await a.sleep_ms(50)
    return n * 2

# Connect the Anvil Uplink. In MicroPython, this call will block forever.

anvil.pico.connect(UPLINK_KEY)


# There's lots more you can do with Anvil on your Pico W.
#
# See https://anvil.works/pico for more information




```

**IR RECEIVER (USED TO RECORD THE SIGNALS FOR EACH FUNCTION)**
ir_rx is uploaded to the RP Pico W. (https://github.com/peterhinch/micropython_ir)
```=python
from ir_rx.acquire import test
test()
```
Attached is all the registered Codes with description on each code's function: https://shorturl.at/jlmCR

**Code for automation of AC and Visual indicator via (RGB Light)**
This code is in seperate file called AUTOAC.py and can be run manually via Thonny. It involves three seperate modes (temperature in degrees celsius):
1. **Temp<18**: The RGB light turns **blue** (Cold)
2. **18<Temp<24**: RGB light turns **green** (desired temp).
4. **Temp>24**: RGB light turns **red** (Warm), IR signal with timings for **Turn On/Off** is sent out to turn on the AC.
```=python
import dht
import machine
import utime

# Initialize DHT11 sensor
tempSensor = dht.DHT11(machine.Pin(17))

# Initialize IR transmitter
ir_transmitter = machine.Pin(18, machine.Pin.OUT)

# Timings for IR signals
toggle_timings = [9093, 4367, 674, 468, 670, 481, 657, 483, 628, 514, 624, 1642, 620, 518, 621, 521, 619, 520, 625, 1639, 618, 1641, 621, 1649, 614, 518, 620, 521, 619, 1667, 595, 1665, 597, 1669, 594, 544, 597, 542, 598, 543, 597, 543, 599, 542, 594, 545, 597, 542, 594, 546, 598, 1670, 603, 1660, 591, 1671, 591, 1666, 596, 1670, 592, 1667, 596, 1671, 592, 1666, 596]

# Function to send custom IR codes
def send_custom_ir_code(pin, timings):
    for i in range(len(timings)):
        if i % 2 == 0:  # If it's an even index, we're dealing with an ON pulse
            pin.on()
        else:  # If it's an odd index, we're dealing with an OFF pulse (space)
            pin.off()
        utime.sleep_us(timings[i])
    pin.off()  # Ensure the IR transmitter is off at the end

# Initialize LED pins
LED_Pin_Red = machine.Pin(28, machine.Pin.OUT)
LED_Pin_Green = machine.Pin(27, machine.Pin.OUT)
LED_Pin_Blue = machine.Pin(26, machine.Pin.OUT)



signal_counter = 0
while True:
    tempSensor.measure()
    temperature = tempSensor.temperature()

    if (temperature >= 24 or temperature <= 18) and signal_counter < 10:
        send_custom_ir_code(ir_transmitter, toggle_timings)
        print("Temperature is {}. Air conditioner toggled".format(temperature))
        signal_counter += 1
        utime.sleep(6)  # Wait for 6 seconds before sending another signal

    if signal_counter == 10:
        print("10 signals sent in the last minute. Waiting for one hour before sending the next set of signals.")
        utime.sleep(3600)  # Wait for an hour before sending another set of signals
        signal_counter = 0  # Reset the counter

    if temperature < 18:
        print("Turning on Blue LED") 
        LED_Pin_Red.value(0)
        LED_Pin_Green.value(0)
        LED_Pin_Blue.value(1)
    elif 18 <= temperature <= 24:
        print("Turning on Green LED") 
        LED_Pin_Red.value(0)
        LED_Pin_Green.value(1)
        LED_Pin_Blue.value(0)
    else:
        print("Turning on Red LED") 
        LED_Pin_Red.value(1)
        LED_Pin_Green.value(0)
        LED_Pin_Blue.value(0)

    utime.sleep(1)  # Check the temperature every second


```
# **Data Transmission**
Data transmission in this project is efficiently handled. Once the Raspberry Pi Pico W connects to Wi-Fi, it establishes a connection to the Anvil WebApp, sending real-time temperature and humidity readings.

On the RP Pico W side, the main.py contains the code for this process:

```=python
import anvil.pico
import uasyncio as a
from machine import Pin
from dht import DHT11

sensor = DHT11(Pin(17))

UPLINK_KEY = "server_HNRJGSIND3LX3-PSCFWVSKM2"


async def record_data():
    while True:
        sensor.measure()
        print(f"T = {sensor.temperature()}, H = {sensor.humidity()}")
        await anvil.pico.call("record_reading", sensor.temperature(), sensor.humidity())
        await a.sleep(1)
        
        
anvil.pico.connect(UPLINK_KEY, on_first_connect=record_data())
```



On the Anvil WebApp side, the relevant code is as follows:

```=python
from ._anvil_designer import Form1Template
from anvil import *
import plotly.graph_objects as go
import anvil.server
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables

class Form1(Form1Template):
  def __init__(self, **properties):
    # Set Form properties and Data Bindings.
    self.init_components(**properties)

    # Any code you write here will run before the form opens.

  
  def timer_1_tick(self, **event_args):
    """This method is called Every [interval] seconds. Does not trigger if [interval] is 0."""
    data = anvil.server.call_s('get_data')

    self.temp_plot.data = go.Scatter(x = [r['when'] for r in data],
                                     y = [r['temperature'] for r in data], fill = 'tozeroy')
    self.hum_plot.data = go.Scatter(x = [r['when'] for r in data],
                                     y = [r['humidity'] for r in data], fill = 'tozeroy')
```


**Data Saving Frequency**
Data is recorded in the database each time a measurement is made. This event-driven design prioritizes user control, recording data as and when required.

**Database Choice**
![](https://hackmd.io/_uploads/HJESqHQFh.png)
For this project, Anvil's integrated Data Tables are used as the database solution. This choice stems from their seamless compatibility with the Anvil WebApp, simplifying data storage and management tasks.

**Automation/Triggers**
Data acquisition in this setup is triggered by server calls. When data is needed for the dashboard graphs, a server call is made, prompting the Raspberry Pi Pico W to measure and send temperature and humidity data. Although this setup emphasizes manual control, it can be modified for automatic data recording at regular intervals or under specific conditions, providing versatility for various application needs.




**Presenting the Data**
In this project, Anvil is utilized for data presentation. The Anvil web app dashboard displays two graphs: one for temperature and another for humidity. Data for these graphs is sourced in real-time from the Raspberry Pi Pico W after a server call is made.

**VISUALIZATION OF TEMP AND HUMID**
![](https://hackmd.io/_uploads/S1o3TS2u3.png)

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

**Shell in Thonny:**
Connecting to Anvil...
Connected
Authenticated to app PS....
T = 26, H = 29
T = 26, H = 29
# **Finalizing the Design**
The main goal was to make this achievable via wifi but in the current state the controller is run manually via Thonny. However, the chosen platform "Anvil" has capabilities for achieving this goal. 

**Final Project Setup**
In finalizing the design of this IoT-based temperature and humidity monitoring system, a strategic setup was critical to ensure all components functioned as expected. The IR transmitter was meticulously mounted directly above the signal receiver on the AC. This placement ensured an unobstructed pathway for the infrared signals, guaranteeing accurate and prompt command execution.

The RGB light was strategically positioned at the front of the AC unit where it was easily visible to occupants of the room. The light offered immediate visual feedback about the temperature and humidity conditions, improving the system's user interface.

The heart of the system, the RP Pico W mounted on the breadboard, was securely fastened to the back of the AC unit using double-sided tape. This placement protected it from environmental interference while enabling it to effectively control the system.

Lastly, the DHT sensor was installed at the back of the AC unit as well. Care was taken to position it so that the air being expelled by the AC unit did not distort its measurements. This ensured that the sensor reliably reported the ambient temperature and humidity levels.

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



# **Reflections**
Reflecting on the project's progression, a key challenge was choosing the right development tools. It involved a certain amount of trial and error, experimenting with various platforms before settling on Thonny and Anvil. In hindsight, spending more time upfront on selecting the most suitable tools could have accelerated the development process. Nonetheless, the experience provided vital insights into choosing appropriate platforms and software.

Despite the challenges, the project was a great learning experience. It provided hands-on experience with hardware-software integration, data visualization, IoT concepts, and above all, problem-solving. While there were moments of struggle, the satisfaction derived from seeing the project reach its completion was unparalleled.

Moving forward, these learnings will prove to be a strong foundation for future projects, helping make more informed choices, planning better, and efficiently solving problems.