# Tutorial: Sensor that measures humidity in soil using Internet of Things Louise Karsten, student credentials: lk223ey In the course "Introduction to Applied Internet of Things" (Linneaus University summer 2020), Internet of Things was introduced to us students both theoretically and practically. After choosing a project that included transmitting and presenting data from some kind of sensor, the final examination was to write a tutorial (with a premade structure) on the project. ## Introduction This tutorial will guide you on how to connect a sensor that measures humidity in soil to WiFi. You will receive both visualized results of the change of water percentage as well as an email notification when the percentage is too low. The estimated time for the project differs for a beginner and someone with experience, approximately two days or a few hours respectively. First, the device is installed and programmed to Ubidots and Atom. When connecting the device to WiFi and placing the sensor in soil, a light indicates the plant’s need of water and the water percentage is displayed on Ubidots. When the percentage of water gets too low, an email is sent to the owner of the plant with a recommendation to water the plant. ## Objective After years of trying to master the art of taking care of plants with them drowning or dying of thirst, it was time for a change. A sensor that somehow would indicate when it would be appropriate to water a plant seemed like the perfect solution. Measuring the humidity in the soil was the way to do it. Not only would this data make it possible to send a signal when it was time to water the plant, but also provide data that could give a valuable insight in how the need of water differs over time. ## Material The material needed for this project can be bought from the website [*electro:kit*](www.electrokit.com) (except for a computer). A list of material and corresponding prices is presented in Table 1. *Table 1. The list of material as well as the prices in SEK.* | Name | Price [SEK] | | ----------------------------------------------------- | ----------- | | [LNU – 1DT305 Tillämpad IoT – LoPy4 and sensors bundle](https://https://www.electrokit.com/produkt/lnu-1dt305-tillampad-iot-sensors-only-bundle1/) | 995.00| | [Soil moisture sensor](https://www.electrokit.com/produkt/jordfuktighetssensor/) | 29.00 From the kit *LNU – 1DT305 Tillämpad IoT – LoPy4 and sensors bundle* the following material is used for the project: * LoPy4 with headers * Expansion board * Micro USB cable * Jumper wire * Breadboard LoPy4 with headers is a development board that is programmable with MicroPython as well as the Pymakr plugins. This makes it suitable for IoT application development. Connecting this device to an expansion board and a micro USB cable gives it power and the opportunity to connect to for example different sensors. The LoPy4 connected to an expansion board is seen in Figure 1. ![](https://i.imgur.com/YKTZao5.png) *Figure 1. The LoPy4 connected to an expansion board.* The soil moisture sensor (see Figure 2) measures the resistance across its two legs. If the soil is dry, the resistance is high and vice versa. This resistance is converted to a voltage that can be read when connected to a microcontroller (such as a LoPy4). ![](https://i.imgur.com/dW2ibpy.png) *Figure 2. The soil moisture sensor and the associated wires.* To simplify the connections between a sensor and the expansion board, a breadboard together with wires can be used. The breadboard used in this project is seen in Figure 3. ![](https://i.imgur.com/zfziQFo.png) *Figure 3. The breadboard used in this project.* ## Computer setup The first step of this project is to install the integrated development environment (IDE) Atom and the Pymakr plugin. An account is created on the website [Ubidots](www.ubidots.com). After this, the device is connected to WiFi by filling in the Ubidots-token and the WiFi credentials into an already made Atom folder. This folder and the different components are written on [this](https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-httpConnecting) webpage. The code needed for the device to send the right data to Ubidots is written in the same *main . py* file (see section *Code*, lines 50-84). When ready, the code is uploaded to the device when the device is connected to the computer via a Micro USB cable. In Ubidots, it is possible to visualize the data that the sensor sends. When Ubidots begins to receive data from the device, an *event* is created in Ubidots. This *event* is an email with a reminder to water the plant that is triggered when the value from the device is lower than 10%. ## Electronic setup The electronics are connected as seen in the figure below: ![](https://i.imgur.com/mKmUVJk.jpg) *Figure 4. The figure shows how the electronics (the LoPy4, the expansion board, the breadboard and the soil moisture sensor) are connected.* The sensor is placed in the soil and connected to ground, 3V3 and P15 on the Pycom expansion board. P15 (pin 15) is chosen because pin 15 will work when running the code (see section *Code* below). 3V3 (the voltage 3.3 V) is chosen because this will be enough power for this sensor. Only a very small part of the breadboard and expansion board is used and it is only connected to WiFi. This means that if another setup was used, this project could be made more effective for production and lower the overall cost. ## Platform The platform used in this project is [Ubidots](www.ubidots.com). Since a LoPy4 with headers and a Pycom expansion board are used in this project (see section *Material*) and Ubidots works well with Pycom products, it is very suitable to use this platform. Only WiFi is used in this project but Ubidots works with for example LoRaWAN as well. It also tracks the location of the device. Ubidots is free for private use, cloud-based and has a 30 days free trial for businesses. In this project only one device is added but there is a possibility to scale the project by adding more devices without any additional fees. Ubidots is similar to the platform [Pybytes](www.pybytes.com) that also tracks the location of the device. Pybytes works with WiFi, LoRa, Bluetooth and LPWAN networks. This platform is free for users, cloud-based and there is a possibility to add as many devices as one would want without paying for it. The main difference between the two platforms Ubidots and Pybytes in this project is that Ubidots has more (as well as nicer) alternatives when it comes to visualizing the data. Receiving an email notification when needing to water the plant is easily done when using Ubidots. If wanting to scale the project it might be preferable with Pybytes since it is always free for users. ## Code ```python= ################### #Written by Ubidots ################### # Code to connect to Ubidots from network import WLAN import urequests as requests import machine import time TOKEN = "Assign_your_Ubidots_token_here" #Put here your TOKEN DELAY = 1 # Delay in seconds wlan = WLAN(mode=WLAN.STA) wlan.antenna(WLAN.INT_ANT) # Assign your Wi-Fi credentials wlan.connect("wifi-SSID-here", auth=(WLAN.WPA2, "wifi-password-here"), timeout=5000) while not wlan.isconnected (): machine.idle() print("Connected to Wifi\n") # Builds the json to send the request def build_json(variable1, value1): try: lat = 6.217 lng = -75.567 data = {variable1: {"value": value1}} return data except: return None # Sends the request. Please reference the REST API reference https://ubidots.com/docs/api/ def post_var(device, value1): try: url = "https://industrial.api.ubidots.com/" url = url + "api/v1.6/devices/" + device headers = {"X-Auth-Token": TOKEN, "Content-Type": "application/json"} data = build_json("Water percentage", value1) if data is not None: print(data) req = requests.post(url=url, headers=headers, json=data) return req.json() else: pass except: pass ############## #Written by me ############## # Code to measure humidity in soil # Import what is necessary import machine import pycom # Prepare for receiving values from the sensor adc = machine.ADC() apin = adc.channel(pin = 'P15',attn = machine.ADC.ATTN_11DB) p_out = machine.Pin('P15', mode = machine.Pin.OUT, pull = machine.Pin.PULL_DOWN) # Define the maximum and minimum values that the sensor will send max = 999 # Completely dry min = 200 # Soaked time.sleep(2) # Wait before starting pycom.heartbeat(False) # Start with LED turned off # Measure the percentage of water in the soil while True: # The measurements are done until the device runs out of battery p_out.value(1) volts = apin.value() # Get a value from the sensor p_out.value(0) percentage_soil = ((int(volts/4.096) - min) * 100) / (max - min) value = 100 - percentage_soil # Percentage of water in the soil if value <= 10: pycom.rgbled(0x7f0000) # If the soil has little water, turn on red light elif value < 80 and value > 10: pycom.rgbled(0x7f7f00) # If the soil has enough water, turn on yellow light elif value >= 80: pycom.rgbled(0x007f00) # If the soil has a lot of water, turn on green light post_var("pycom", value) machine.sleep(60*60*1000, True) # Wait one hour until continuing with the next measurement, time in ms ``` ## Transmitting data Data is sent to Ubidots once an hour. This can be seen in section *Code* (line 84) where it says ”machine.sleep(60 * 60 * 1000, True)”, where the device waits one hour before measuring again. While waiting to send more data, the device goes into a power saving mode. When entering this mode, WiFi is switched of and after the given time it is turned back on. The frequency of sending data does not have to be very high as the percentage of water in the soil does not differ that much over time. When the device transmits data of a water percentage lower than 10% to Ubidots, an event is triggered in Ubidots. This event will automatically send an email to the plant owner that it is time to water the plant. The wireless protocol used in this project is WiFi (2.4 GHz). Since the device is located too far away from a LoRa gateway there is no possibility of using LoRa. Transmitting data to the internet via WiFi works well in this project since it is a common wireless protocol. Therefore it works well even when situated in the middle of nowhere (where WiFi still can be accessed via an internet sharing device like a smart phone). The security of a WiFi connection is low since someone within range of it only needs a password to gain access to the connection. This security issue is not a problem in this project because the device only needs the WiFi to transmit data to Ubidots. Transmitting the data will still be possible even if someone else uses the same WiFi connection. MQTT is used as the transport protocol. This protocol defines the two network entities message broker and client. The broker can be compared to a post-office, it receives messages from the client and sends the messages to destination clients. Information sent via MQTT is organised with topics, different clients subscribe to different topics. Advantages of using MQTT as a transport protocol are that it is lightweight and flexible. ## Presenting data To present the data, the dashboard in Ubidots is used. A value of the percentage of water in the soil is sent to Ubidots once an hour when the device is turned on. These values are then presented in a line chart where it is easy to follow the changes of the water percentage in the soil over time, see Figure 5 below. Figure 5 also shows how the last data value that Ubidots receives is displayed. The last 10 values are preserved in the database. Since no analyse other than when it is time to water the plants is being made, there is no need for the data to be saved longer. Saving more data points than necessary only takes up space. ![](https://i.imgur.com/GnZtYJC.png) *Figure 5. The plot to the left presents how the water percentage in the soil changes over time. The symbol to the right shows the last value sent to Ubidots of the water percentage in the soil.* ## Finalizing design When the soil is dry (has a water percentage between 0-10%) the red light on the LoPy4 is turned on. This is to indicate that it is time to water the plant. If a red light is turned on, an email is also sent to the plant owner, see figure 6 below. ![](https://i.imgur.com/NHJnwmT.png) *Figure 6. The figure shows the email notification that is sent when it is time to water the plant.* When pouring water on the soil, the water percentage will increase and while it is moist (10-80%) a yellow light will turn on. After watering the plant, there is a lot of water in the soil (the percentage of water is 80-100%) and therefore the plant does not need to be taken care of so a green light will be turned on. Figure 7 below shows how this looks in real life. ![](https://i.imgur.com/e5NqsV4.jpg) *Figure 7. The figure shows how the light turns red if it is completely dry, yellow if it needs a little more water and green when the watering is done.* ## Final thoughts The project worked out the way it was planned, perhaps a more precise study of exactly at what percentage the soil needs more water could have been calculated. Over time the sensor gets damaged if operated permanently. If wanting to leave the sensor in with power on to measure the water percentage in the soil, another sensor than this one should be used.