# Temperature control ## Emil Solin ### ef222ut ### 1DT305 ST 21 ### Linnaeus University --- Estimated time of build: **2h** ## Dislaimer **This project uses mains voltage, 230VAC, which is potentially lethal. If you are going to follow along in this tutorial you should have prior experience of handling high voltages and be extremely careful. Proceed at your own risk.** ## Introduction In this tutorial we will go through how to build and set up an IoT-device which meassures temperature and humidity and has the ability to control devices connected to mains voltage. ## Objectives The goal of this project is to turn on and off a device connected to mains voltage (in Sweden 230VAC) and to get temperature and humidity readings, with the help of a microcontroller connected to the internet, in this case the Pycom LoPy4. The project will later be used to turn on and off the heating in a cabin. Most of the required hardware is already in place for this and is now controlled via text messages over the cellular network, which will be replaced with this project. This means that the feedback from the system will be much snappier and it will also be easy to add more functionality later. ## Material | Quantity | Component | Info | | -------- | -------- | -------- | | 1 | [Red LED](https://www.electrokit.com/produkt/led-5mm-rod-diffus-1500mcd/) | Indicates that the relay is off | | 1 | [Green LED](https://www.electrokit.com/produkt/led-5mm-pure-gron-diffus/) | Indicates that the relay is on | | 1 | [Resistor 390 Ω](https://www.electrokit.com/produkt/motstand-kolfilm-0-25w-390ohm-390r/) | Limiting the current to the LED's | | 1 | [DHT 11 Humidity & Temperature Sensor](https://www.electrokit.com/produkt/digital-temperatur-och-fuktsensor-dht11/) | Used for temperature and humidity readings | | 1 | [SRD-05VDC-SL-C Relay module](https://www.electrokit.com/produkt/relamodul-5v/) | Used to control a high voltage | | 1 | [2n7000 Field Emitting Transistor (FET)](https://www.electrokit.com/produkt/2n7000-to-92-n-ch-60v-200ma/) | Used to control the relay. | | 1 | [Push button](https://www.electrokit.com/produkt/knappar-pcb-sortiment-12st/) | Used to control the relay physically | | 1 | [Pycom LoPy4](https://pycom.io/product/lopy4/) | Used to control everything with software | | 1 | [Pycom Expansion Board 3.0](https://pycom.io/product/expansion-board-3-0/) | Connecting the LoPy4 to the computer when programming it | *Table 1. Components* ### Component sourcing All components are bought at electrokit.se through kits, [Komponentsats grund](https://www.electrokit.com/produkt/komponentsats-grund/), [Komponentsats - Bra att ha](https://www.electrokit.com/produkt/komponentsats-bra-att-ha/) and [LNU – 1DT305 Tillämpad IoT – LoPy4 and sensors bundle](https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-lopy4-and-sensors-bundle/). However, the LNU kit was special for this course and is not available. Electrokit also does not offer any Pycom products to the general public. Total cost of the kits: **1247 sek.** Total cost of individual components from Electrokit.se and Pycom.io: **767 sek.** *The costs are calculated with prices and exchange rates as of 2021-08-02 and does not include shipping fees, nor taxes in case of Pycom.io (not EU).* ## Computer setup All programming has been conducted on a Linux machine, Pop!_os, and Visual Studio Code as IDE. The pymakr plugin is installed in vscode to have access to the REPL-console and easily run and upload the code to the microcontroler. ### Setup First install Visual Studio Code by downloading the installer from https://code.visualstudio.com/Download and run the installer. Then install node.js. The easiest way of doing this on an ubuntu based system, such as Pop!_os, is to run the following command in a terminal: ``` bash= curl -fsSL https://deb.nodesource.com/setup_current.x | sudo -E bash - sudo apt-get install -y nodejs ``` This will install the current version of node on your computer. The next step is to install the pymakr plugin for vscode. Open the Extensions tab and search for pymakr and install the plugin. |![](https://i.imgur.com/qancUzU.png)| |:--:| |*Figure 1. Installing pymakr-plugin*| If your Pycom-device's firmware is not up to date you should update it. This can easily be done using the Pycom updater software which you can [download here](https://pycom.io/downloads/). When the updater is installed, open it, connect your pycom device to the computer, close vscode (to not interfere with the updater) and just click continue and install. ## Putting everything together ### The LED's The LED's needs a current limiting resistor in order to not break when powered on. Both the used LED's are rated for 25mA. The voltage from the pins are 3.3V. To calculate which resistance value needed we can use ohms law (V/I = R) ``` 3.3 / 0.025 = 132 ``` However, the I/O-pins of the LoPy4 are rated at 12mA max and 6mA recommended. ``` 3.3 / 0.006 = 550 ``` This means 550 Ω would be ideal, but since I had 390 Ω at hand i chose that. This gives us a current of 8.5mA ### The DHT 11 sensor The DHT 11 can be powered with 3.3 to 5.5 volts. However, since the LoPy4's I/O-pins are only tolerant up to 3.3V input it is best to use 3.3V to power the sensor. > If you are using the DHT 11 as it is, ie, not the module, you may need to wire it somewhat differently and add a resistor. ### The relay The relay is used to control a high voltage. Relays control a higher voltage or current with a smaller signal and the circuits are galvanically isolated. It can be a 230V low current signal controling a 230V high current. Or in this case, a low voltage (5V) and relatively low current, controling a high voltage (230v) and high current, up to 10A. ### The FET (Field Emitting Transistor) The FET is used to control the relay. Since the LoPy4 only handles 3.3V and a maximum output current of 12mA on its I/O-pins and the relay needs 5V and has a current draw of about 80mA we need to use a transistor to drive the relay. The gate of the FET is connected to an I/O-pin of the LoPy4, which then can control the higher voltage (5V) of the relay. ### The push button The push button is used to control the relay physically. |![](https://i.imgur.com/B7hLw1I.jpg)| |:--:| | *Figure 2. Schematic of the circuit* | ## Platform The platform used in this project is node-red running in a docker environment on the local machine. Node-red is a great tool for an IoT-beginner programmer. It is possible to install lots of plugins directly in the docker container. ### Docker Docker should come preinstalled on newer variants of ubuntu based linux-distros. However, if you need to install it anyway you may follow the guide at https://docs.docker.com/engine/install/ubuntu/. ### Node-red Before starting the container you should create a folder where you want to save all the configurations from the node-red container, example, ~/workspace/node-red, and enter that folder in a terminal. To start a node-red docker container you can then use the following command: ``` bash= docker run --rm -it -p 1880:1880 -p 1883:1883 -v $(pwd):/data --name node-red-1 nodered/node-red ``` This command starts a container named "node-red-1" and binds the "/data"-directory inside the container to the directory you are currently in (~/workspace/node-red). The ports 1880 and 1883 are also ported to the local machine's ports. When you stop the container it will be removed, since we used the "--rm" option, but all the data, configurations, flows and installed plugins will be saved on your local drive in the directory we specified. When we want to start node-red again we simply use the same command. Just make sure you are standing in the node-red directory we created earlier or specify it with an absolute path (/home/your_username/workspace/node-red). ### MQTT-broker To be able to use MQTT-clients we need a broker. Since we are using node-red it is easy to install a broker. I have chosen Aedes. To install it open localhost:1880 in your web browser of choice. Here we find the node-red web interface. Click on the menu and select "Manage palette". Click on the "Install" tab and search for "aedes" and click install on "node-red-contrib-aedes". This will install the broker and add it to the package.json file and to the node_modules folder in the directory you have attached to your docker container. This means that when you start the container next time, it will already be installed, super convenient. ### Setting up flows Now we need to setup a flow. Start by searching for "aedes" in the search bar on the left and click and drag the "aedes broker" node and place in your flow. |![](https://i.imgur.com/9e7pjhU.png)| |:--:| |*Figure 3. Adding aedes broker node to flow*| Double click the node and make sure port 1883 is used. Enter the "Security" tab and choose a username and password. If this is not going to be used in production you may skip that. ### MQTT-client In this project I have used an already existing MQTT-client mobile application named MQTT Dash. In this application we can connect to the broker by using the host computer's ip-address and port 1883 and the username and password we set up earlier. Then we need to subscribe and publish to the topics we decide to set up in the source code. *Note: We need to be connected to the same network as the host computer in order to access it by its internal ip-address.* ## The code The source code can be found at gitlab.com/esolin/temp-control. Since the code should keep track of incoming messages, if the button has been clicked as well as handling the sensor, the program is running on three threads. ### The switch The code for the switch is started in a separate thread ``` python= def switch_th(id): while True: try: while (switch() == 0): machine.idle() relay.toggle() set_state() except Exception: print('Something bad just happened with the switch') time.sleep(1) _thread.start_new_thread(switch_th, (thread_nr,)) ``` ### The sensor The code for the sensor is started in a separate thread. When the values have been read they are published to the topics "temperature" and "humidity". The readings are made every 60 seconds. ``` python= def sensor_th(id): time.sleep(2) while True: try: result = sensor.read() while not result.is_valid(): time.sleep(.5) result = sensor.read() client.publish( topic=config.TOPIC_PUB_TEMP, msg=str(result.temperature) ) client.publish( topic=config.TOPIC_PUB_HUMIDITY, msg=str(result.humidity) ) except Exception: print('Something bad just happened with the sensor') time.sleep(60) _thread.start_new_thread(sensor_th, (thread_nr,)) ``` ### The MQTT-subscriber The code for the MQTT-subscribe part is what is running in the main thread. In the sub_cb callback function we are checking if the value of the "power_on" topic is "true" or "false". If true, the relay-pin is set to high, else low. This will then trigger the MQTT-publisher. ``` python= def sub_cb(topic, power_on): power = power_on.decode('utf-8') if (power == 'true'): relay(1) else: relay(0) client.set_callback(sub_cb) client.connect() client.subscribe(topic=config.TOPIC_SUB_POWER) while True: try: client.wait_msg() set_state() except Exception: print('Something bad just happened with mqtt') time.sleep(1) ``` ### The MQTT-publisher There are two parts of the MQTT-publisher. One part is running in the sensor thread. The other is triggered when the relay value changes. If the value of the relay-pin is high the green LED will light up and the MQTT-client will publish "true" on the topic "is_on". If the value of the relay-pin is set to low the red LED will light up and the MQTT-client will publish "false" on the topic "is_on". ``` python= def set_state(): if (relay() == 1): led_green(1) led_red(0) client.publish( topic=config.TOPIC_PUB_IS_ON, msg='true' ) else: led_red(1) led_green(0) client.publish( topic=config.TOPIC_PUB_IS_ON, msg='false' ) ``` ## Transmitting data The data is transmitted via Wifi using MQTT. MQTT is a lighweight protocol which is popular within the IoT world. The data from the DHT 11 sensor is transmitted once every minute. The data for switching the relay is transmitted only when the state is changed, ie, when a user is switching on or off either by pressing the physical button on the board or when using an MQTT-client to send the command. ## Presenting the data To present the data and send commands a mobile application has been used as a MQTT-client, MQTT Dash. In the app it is possible to add switches, text images and more. |![](https://i.imgur.com/LYS2r6I.jpg)| |:--:| |*Figure 4. Screenshot of the dashboard in MQTT Dash when power is off*| |![](https://i.imgur.com/cEC5n3F.jpg)| |:--:| |*Figure 5. Screenshot of the dashboard in MQTT Dash when switching the power*| |![](https://i.imgur.com/wPGUPuw.jpg)| |:--:| |*Figure 6. Screenshot of the dashboard in MQTT Dash when power is on*| ### Persisting data There are currently no database in use for persistance of data. In the future it might be added. ## Finalizing the design The final product of the project is still in a lab environment. The circuit is on a breadboard and to test that the circuit actually works as intended a lightbulb is connected to the relay to simulate the 230V load. This can be seen in the video linked below. |![](https://i.imgur.com/kz9Bfwh.jpg)| |:--:| |*Figure 7. Picture of the circuit*| A very short demo of the project, showing how it is used, [can be found here](https://youtu.be/yvfCG41KMD8). Note the light that comes on in the upper right of the screen when the power is turned on. ### Future The circuit should be transferred to some kind of circuit board and be mounted in a case. In the "production environment", ie the cabin, the relay will control other relays which turns on and off the heating.
{"metaMigratedAt":"2023-06-16T05:46:08.306Z","metaMigratedFrom":"YAML","title":"Temperature control","breaks":true,"contributors":"[{\"id\":\"addb9ce6-818a-477f-91b0-a18d8c021365\",\"add\":17499,\"del\":2995}]","description":"Estimated time of build: 2h"}
    245 views