###### Author: `Anahita Keshvari (ak225hz)` ###### tags: `IoT` `MQTT` `Mosquitto` `Node-Red` `InfluxDB` This tutorial provides a comprehensive guide to creating automated plant monitoring. It outlines the necessary steps to gather sensor data, such as temperature, humidity, soil moisture, and light intensity, from both the environment and the plants themselves. The collected data is then stored in InfluxDB for easy access and analysis. The tutorial also demonstrates how to utilize a visualization user interface to monitor updates and changes in the plant's environment effectively. By following this tutorial, you will be able to develop your own automated plant monitoring system with data storage and visualization capabilities, enabling you to track and analyze crucial environmental factors for optimal plant growth. By possessing a fundamental knowledge of microcontrollers, micro Python programming, and Linux administration, you should be capable of completing this project in around ten to fifteen hours. ## Objective We built this automated plant monitoring device to help people take better care of their plants. The purpose of this device is to gather sensor data, including temperature, humidity, soil moisture, and light intensity, from the environment and the plants themselves. By collecting and analyzing this data, we aim to provide valuable insights into the plant's growing conditions and enable optimal plant growth. The insights derived from the data will enable users to make informed decisions regarding plant care and management. For example, by analyzing the temperature and humidity data, users can identify optimal growing conditions for specific plants or detect potential issues such as excessive heat or moisture. Soil moisture data can help determine the appropriate watering schedule, preventing under or over-watering. Light intensity data can assist in optimizing the positioning of plants for adequate sunlight exposure. Overall, this automated plant monitoring system aims to empower users with actionable insights to enhance plant care, optimize growth conditions, and ultimately achieve healthier and more productive plants. ### Material The following materials used in this project: | Hardware | Price and Purchase Link | | ------------------------- |:----------------------- | | ![](https://hackmd.io/_uploads/B16O98gF3.png =150x) Raspberry Pi Pico W | [98 SEK](https://www.electrokit.com/en/product/raspberry-pi-pico-w/)| |![](https://i.imgur.com/Z3sDGJA.png =120x) DHT22 temperature & moisture sensor | [108 SEK](https://amzn.eu/d/7lDWe01) | | ![](https://hackmd.io/_uploads/SJ5ga8xK3.png =150x) Dallas DS18B20 temperature sensor | [160 SEK](https://www.kjell.com/se/produkter/el-verktyg/elektronik/utvecklingskit/arduino/arduino-tillbehor/temperatursensor-med-kabel-for-arduino-p87081) | | ![](https://hackmd.io/_uploads/HkyzA8gYn.png =120x) Photoresistor (LDR) sensor | [36 SEK](https://www.conrad.se/p/ljusmotstand-1485310-arduino-1485310) | | ![](https://hackmd.io/_uploads/r1ZkkDeYh.png) Soil moisture senosr | [64 SEK](https://amzn.eu/d/2V4oKHh) | |![](https://hackmd.io/_uploads/H1zXO-XYn.png =120x) 5v relay| [39 SEK](https://www.electrokit.com/en/product/relay-module-5v/) | | ![](https://hackmd.io/_uploads/r14ttWmFh.png =120x) | [149 SEK](https://www.ikea.com/se/sv/p/vaexer-led-ljuskaella-foer-odling-par30-e27-80540194/) | ![](https://hackmd.io/_uploads/Sy9K7OxFn.png =220x) CentOS Stream 8 Virtual Machine | [~50 SEK/Month](https://www.digitalocean.com/pricing) | | | **Total 704 SEK**| In this project, I have used Raspberry Pi Pico W as a microcontroller to read the value of the following sensor and used a self-hosting solution with Digital Ocean Linux CentOS 8 Stream Virtual Machine to install software on. + **DHT22:** is used to measure both temperature and humidity in a room. + **Dallas DS18B20:** This is an analog sensor used to measure temperature and it helps to validate the temperature values recorded by DHT22. + **Light Dependent Resistor (LDR):** Used to measure the darkness of the place you put your plants and help you with understanding how light could affect the healthiness of the sensor. + **Soil Moisture:** It measures volumetric water content in the soil and helps you understand in what condition the plant grows better. ## Computer Setup ### Flashing Raspberry Pi Pico W Firmware MicroPython was chosen as the programming language for this project. Raspberry Pi Pico W comes without any operating system on it and we used the steps in [**this tutorial**](https://hackmd.io/@lnu-iot/rkFw7gao_) to flash it with MicroPython. After flashing the board, we can access the REPL (Read-Evaluate-Print Loop) to test and upload our code to the Raspberry Pi Pico W. ### Installing IDE and Uploading Code I could not install [VS Code](https://code.visualstudio.com/) on my computer as it is my work system and it needed admin access to install it. Therefore, I installed [**Thonny**](https://thonny.org/) which does not need admin access. Installing it is straightforward and is like other Windows applications. The first time you open Thonny, you should navigate to `View >> Files` to activate the file explorer panel. Then we need to navigate to `Run >> Select interpreter…` and under the `interpreter` tab choose `MicroPython (Raspberry Pi Pico)` from the upper drop-down list and choose the microcontroller port from the lower drop-down list. ![](https://hackmd.io/_uploads/B1Ht3Oxth.png =400x) Now we can open local MicroPython files from our computer in the upper-left panel and see the file structures of existing files in Raspberry Pi Pico W in the lower-left panel. By right click on the local files, we can choose `Upload to /` to upload the local file to the microcontroller. If you have an ongoing program like a `while true loop` you probably need to stop the code in the `Terminal` by clicking `Ctrl+c` to be able to upload your code. ![](https://hackmd.io/_uploads/HJQLJtgK3.png =500x) ## Putting everything together The hardware has been connected together on a Breadboard with jumper wire like following sketch and we used [**Fritzing**](https://fritzing.org/) to draw the following diagram: <br/> ![](https://hackmd.io/_uploads/Bk-tiW7Kn.jpg) <br/> The following diagram is the deployment view of the system. Raspberry Pi both publish sensors value to Mosquitto and subscribe to get the ON/OFF command which turns the onboard LED on/off and also is connected to a relay controlling a UV Lamp. Node-Red also subscribes to the topics to fetch data values and save them into the database and we have used a dashboard extension to visualize data for the user. <br/> ![](https://hackmd.io/_uploads/BJmv2ZXYn.jpg) <br/> ### Electrical Calculations There are several sensors used in this project and each of them comes from different manufacturers without proper documentation about the power consumption. To run the Raspberry Pi Pico W on the battery we must know how much energy does it consume on average while running the code. There are several things affecting this power consumption including used sensors, the code, and the communication medium in this case WiFi. Some microcontrollers support different levels of sleep to save the battery while there is no code execution. Unfortunately, Raspberry Pi Pico can not react to any time-related action for more than approximately 8 seconds. We tried to use some deep sleep on the board but it is unpredictable and even while using light sleep for more than eight seconds it returned randomly. We find out by using WDT (Watch Dog Timer) which only could be set to approximately 8000 milliseconds. We decided to connect the sensors, write the code and run it while giving power to it with a power profiler. The following diagram is captured from Power Profiler Kit II from Nordic Semiconductor and it gives us the average energy consumption of the microcontroller around 67mAh. ![](https://hackmd.io/_uploads/rku49cxth.jpg) <br/> Based on the power consumption of current settings if we have a battery like [**this**](https://www.electrokit.com/produkt/batteri-lipo-3-7v-6600mah/) with 6600mAh charge then we can run our code for `6600 / 67 = 98 Hours` which is around 4 days. If we use a stronger power bank like [**this**](https://www.teknikdelar.se/produkt/sign-powerbank-30.000-mah-usb-c-usb-c) that can hold 30,000 mAh charge then we can run the code for `30000 / 67 = 447 Hours` which is around 18 days. As it could be observed the Raspberry Pi Pico is not power consumption friendly and we do not suggest using it with batteries. ## Platform We first tested [**Adafruit**](https://io.adafruit.com/) and [**Ubidots**](https://ubidots.com/) to see how other platforms handle device integration and Dashboards. It gave us some valuable ideas about what each platform has to offer. For example, Adafruit uses MQTT as the communication protocol and utilizes different time-based and value-based alarm triggering. Ubidots uses both MQTT and REST API for uploading data, and more integration options to connect it to different platforms like [**The Things Stack (TTS)**](https://www.thethingsindustries.com/). The mentioned platforms have restrictions on saving data for a long time Adafruit retains data for 7 days in free device registrations. To keep the data as long as we need it and have a better understanding of changes in plant growth I decided to use the self-hosting solutions. This gives us the opportunity to scale up things in the future. **Node-Red** and **InfluxDB** were selected to save data in a Virtual Linux. The platforms and software are presented in the following sections. ## The Code In section [**Putting everything together**](#Putting-everything-together) it is visible in the deployment view of the system that we have Raspberry Pi Pico W using WiFi and sending/receiving messages to Mosquitto MQTT broker. The code was uploaded to the [**GitHub here**](https://github.com/anahit-aaaa/LNU_Project) and commented thoroughly to be self-explanatory and the brief functionality is presented here. The file structure for our node is the following: ``` Raspberry Pi Root |-lib | |-config.py | |-mqtt.py | |-sensors.py | |-wifiConnection.py |-main.py ``` The `config.py` holds all the keys and constants, we save WiFi credentials, MQTT server address, port, credentials, and MQTT topics addresses. `mqtt.py` holds functions required to connect to the MQTT broker both publish messages and subscribe to the topics. In our code, we publish sensor data to the broker and subscribe to the light topic to listen to commands coming from the broker to control the LED. `sensors.py` save functions to read from each individual sensor and return the value to the callee. `wifiConnection.py` is used both to initialize a WDT (Watch Dog Timer) to be used when a part of code fails and has two functions `connect()` and `disconnect()` from the local WiFi. Finally, `main.py` is the place where the code starts its execution and is responsible to initialize required variables, connecting to WiFi, connecting to the MQTT server, and both publishing and subscribing messages. The following code snipped is the initialization of WDT initialized/used in `wifiConnection.py` and also used in `main.py` to make the sensor robust while some error stops code executions. ```python=- from machine import WDT watchdog = WDT(timeout=config.8000) watchdog.feed() ``` ## Transmitting the data / connectivity I use an indoor system therefore I did not find any use for LoRa modules as WiFi covers all indoor areas. To send the data we followed the steps presented in [**this tutorial**](https://hackmd.io/@lnu-iot/rJr_nGyq5) to install Mosquitto. Mosquitto Broker is an open-source message broker that implements the MQTT protocol. It acts as a central hub for communication between devices and applications in IoT systems. It allows devices to publish messages on specific topics and enables other devices or applications to subscribe to those topics to receive the messages. Mosquitto Broker handles the routing and delivery of messages, ensuring reliable communication. It is lightweight, efficient, and widely used in IoT applications. MQTT is more beneficial than HTTP for IoT and real-time messaging because it is lightweight, efficient, and optimized for low network and power usage. It allows for asynchronous and real-time communication, follows a publish-subscribe architecture for scalable message distribution, offers reliable message delivery options, supports persistent connections, and is highly scalable. These advantages make MQTT ideal for IoT applications and scenarios requiring efficient, real-time communication. Mosquitto broker uses MQTT topics that are strings used to categorize messages in MQTT. They follow a hierarchical structure and allow publishers to send messages to specific topics, while subscribers can choose which topics they want to receive messages from. Topics enable efficient message routing and filtering in MQTT-based systems. We give users authorized users to publish/subscribe to topics starting with `devices/#` which means they can post everything under the “devices/” topic path. The data is transmitted every 20 seconds for this prototype and we plan to increase it to every 10 minutes in the final product to save more energy and reduce the power consumption lower than 67mAh. <br/> ## Presenting the data We use the following applications/services in Linux to gather and visualize data: ![](https://hackmd.io/_uploads/rkglthxF2.png =80x) **Node-RED** is an open-source tool that allows users to visually create applications by connecting nodes. It provides a web-based interface for drag-and-drop programming and offers a wide range of built-in nodes for various functionalities. Node-RED is popular for IoT projects and automation tasks due to its ease of use and extensibility. The benefits of Node-RED include its visual programming interface, ease of use, extensive library of pre-built nodes, integration capabilities, event-driven architecture, deployment flexibility, and active community support. ![](https://hackmd.io/_uploads/r15I6Z7t2.jpg) <br/><br/> ![](https://hackmd.io/_uploads/H14t9netn.jpg =80x) **Node-RED Dashboard** is an extension for Node-RED that enables the creation of real-time web dashboards. It offers pre-built user interface components for visualizing and controlling data, supports real-time updates, allows customization of the dashboard layout, and facilitates user input handling. It enhances Node-RED by providing an intuitive interface for building interactive dashboards. <br/> ![](https://i.imgur.com/tceyts1.png =100x) **InfluxDB** is a database specifically designed for storing and analyzing data that changes over time, such as sensor readings or metrics. It is really good at handling a lot of data quickly. It has a special language for querying and analyzing this type of data. InfluxDB can be used for things like monitoring and tracking systems, IoT devices, or any application that involves collecting and analyzing time-based data. All coming data to the subscribed topics will be saved into the database which is now every 20 seconds and will be changed to every 10 minutes in the final product. ![](https://hackmd.io/_uploads/HyvvxzQtn.jpg) <br/> ### Automation and Data Trigger in Node-Red Dashboard We can control the Raspberry Pi Pico W onboard LED from the Node-Red dashboard and also with a relay to control a UV light shining on the plants for a couple of hours each day. There are two ways to control the LED, one is the manual toggle button in the dashboard that will send an ON/OFF signal to the Raspberry Pi. There is also an automated trigger based on the time of the day to send an ON/OFF Signal both changing the state of the visual part of the dashboard and to the Raspberry Pi to control the LED. It is set to turn off LED between `00:00 - 17:00 and 21:00 - 24:00`. It also sends a turn-on command to the LED between `17:00 - 21:00`. These settings make the lamp three hours active each day and it triggers once an hour to make sure the state keeps the same. We also installed a Discord node to trigger when the soil moisture goes below 10 % to send an alarm to the Discord bot. <br/> ![](https://hackmd.io/_uploads/HkS2AbXY3.jpg) <br/> The plan is to use the `Big Timer` (The light green node in the above image) which is a more advanced trigger system to send ON/OFF commands to schedule all year round. <br/> ## Final Design Here are images of our finalized hardware: The Gateway | The Gateway :-------------------------: | :-------------------------: ![](https://hackmd.io/_uploads/BydDwtZth.jpg) | ![](https://hackmd.io/_uploads/ByDtDt-th.jpg) ![](https://hackmd.io/_uploads/B1rnPF-K3.jpg) | ![](https://hackmd.io/_uploads/SyLRPF-th.jpg) ![](https://hackmd.io/_uploads/rJGZyfQYh.jpg) <br/> Some images of Dashboard examples: This is the upper part of the dashboard captured at night. (visible in darkness gauge) ![](https://hackmd.io/_uploads/S1nliheY2.png) <br/> This is the lower part of the dashboard captured in daylight. (visible in darkness gauge) ![](https://hackmd.io/_uploads/HJI2tFWFh.png) <br/><br/> ## Lesson Learned & Further Optimization This is a prototype of my plant monitoring system and I plan to add more sensors for my other plant pots. Then add more actuators to the project and collect data for a future machine learner to find what is the best condition for plant monitoring.