# Tutorial for soil moisture sensor!
**Author:** Daniel Wärulf, dw222gz
This tutorial will cover how you can setup your own sensor and see how dry your soil is with the use of AdaFruit IO to display your result to the public!
If you have earlier experience of this kind of stuff, using sensors and NodeMCU:s as well as coding in MicroPython, you would finish this within a few hours following this tutorial.
## Table of content
- Table of Content
[ToC]
## Object
The object of this project is to create a visualization of how dry/wet your soil is, so you can determine if you need to water your plants or not.
Why I chose this project was because of the tight budget I had. I needed a small simple project that was fairly easy to make and still come to use. Thats when I settled for this project. It was a fun start into the world of IoT and microcontrollers, and it with some difficulty it worked out nice. I also like plants, and to create something that might assist me in taking care of them was just a plus on the side!
By completing this project I will gain an understanding of using a microcontroller with micropython and sending data through MQTT.
## Materials
The table below shows what I used in this project, where I bought them, what use they had in the project, and the price of each component.
| Product | Where to buy |Description |Price
| ----------- |:----------------------- |:------------ |:--------
| NodeMCU V3 | [:link:][Node] |Microcontroller able to run MicroPython | 149Kr
| Soil hygrometer module | [:link:][Soil] |Measures the resistance in the soil and sends it through the sensor |29kr
| 400 Channel breadboard | [:link:][Bread] |To connect everything |99Kr
| Jumper wires 1-pin male-male 150mm 10-pack | [:link:][Wire]|Used to connect the things on the breadboard |29 Kr
| | | |Tot: 366 Kr
|*A Micro-USB charger is also needed, not included as I already had one | | |
[Node]: https://www.electrokit.com/produkt/nodemcu-v3/
[Soil]: https://www.electrokit.com/produkt/jordfuktighetssensor/
[Bread]: https://www.kjell.com/se/produkter/el-verktyg/elektronik/elektroniklabb/luxorparts-kopplingsdack-400-anslutningar-2-pack-p36283?gclid=Cj0KCQjwn4qWBhCvARIsAFNAMiivznH8ugeHKTC75NPWGTaBYC0tfWSb3mAC9MY1wrWrnxgSo4C77PoaAipDEALw_wcB&gclsrc=aw.ds
[Wire]: https://www.electrokit.com/en/product/jumper-wires-1-pin-male-male-150mm-10-pack/
The reason for the NodeMCU ESP8266 microcontroller was used is because it is a cheap and simple little machine to work with. It did what it needed to do and nothing more, very fitting for this project.
## Computer Setup
The IDE I chose for this project was the Thonny IDE. Thonny IDE is a great entry point for programming microcontrollers such as the ESP8266 with the use of MicroPython. Thonny also lets you flash the microcontroller with a few button clicks, as you need to flash the ESP8266 with the MicroPython firmware.
Below, I will show you in pictures how to properly set up Thonny and flash the microcontroller to let the user program using MicroPython.
### Installing the IDE
The first thing you need to do is install Thonny IDE, which you can to [here][IDE]! The Ide works for Windows, Mac, and Linux.

[IDE]: https://thonny.org/
### Flashing the ESP8266
When you have the IDE installed, you need to flash the microcontroller with the latest MicroPython firmware. You can find that [here][Firm], depending on your microcontroller, the link is for the ESP8266.

[Firm]: https://micropython.org/download/esp8266/
When you have the latest firmware downloaded, you can go into Thonny and continue through the next steps.
The first thing you want to do to download the firmware is go to the bottom right, and choose "configure interpreter" shown in the picture below.

This will open up the next menu shown.

Here you want to select "Install or update firmware". This will take you to the next picture.

Here you select the port your ESP8266 or other microcontroller is on, as well as the firmware you recently downloaded. When That is chosen, you click install and wait. When everything is finished, you can cancel the latest window, and then click ok on the prior. The last thing you need to do then is just select the correct MicroPython in the bottom right corner, and you are all set to start programming!
If you encounter any problems on the way, and want to see in a video how this is done, I recommend to watch [this][Video] video!
[Video]: https://www.youtube.com/watch?v=fmgQ8Dcg9uM&ab_channel=KevinMcAleer
### How to upload code to the Controller
To upload the code to the microcontroller, you only have to right click on the .py file in you file explorer in Thonny IDE, and then choose "Upload to /" as seen in the picture below.

## Putting everything together
Below is a picture of the circuit diagram. Note that this is only from part to part, but I have done it with a breadboard, which doesn't make a big difference in the connections. I will include a picture of that as well!


Here are how the cables goes:
- Black cable: Ground to Ground
- Red cable: VCC on sensor to 3V3
- Blue Cable: A0 to A0
The cables to the earth sensor doesn't matter how they are connected (The orange+yellow cable).
## Platform used (AdaFruit IO)
I chose to use AdaFruit for this project, as it is simple and easy to connect to. AdaFruit IO is a MQTT broker, with a dashboard which is easy to use.
Adafruit offers the user the list below for free, which is another primary reason for my choice.
– **30** data points per minute
– **30** days of data storage
– Actions every **15** minutes
– **5** dashboards
– **2** WipperSnapper devices
– **5** groups
– **10** feeds
You can create a account [here][Ada]!
[Ada]: https://io.adafruit.com/Wrulf00/wippersnapper
## The code
The code for this project is not an impossible task, but come with some difficulties if this is the first time using MicroPython.
What you need to download for this to work as it is supposed to, you need to copy the umqttsimple library from [this github][This].
[This]: https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py
Once that is done and the umqttsimple library is in the same directory as the other .py files, we begin to include the needed imports, as shown in the code snippet below.
```javascript=1
import network
from network import WLAN # For operation of WiFi network
import time # Base library for Pycom devices
from umqttsimple import MQTTClient # For use of MQTT protocol to talk to Adafruit IO
import ubinascii # Needed to run any MicroPython code
import machine # Interfaces with hardware components
import micropython # Needed to run any MicroPython code
import machine
from machine import ADC
from time import sleep
```
We can then start the process of hooking up the MicroPython to your WiFi, this is done by the code shown below.
```javascript=11
ssid = "YOUR_SSID"
password = "YOUR_PASSWORD"
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print('Connecting...')
# Enable the interface
sta_if.active(True)
# Connect
sta_if.connect(ssid, password)
# Wait till connection is established
while not sta_if.isconnected():
pass
print('It is now connected.')
else:
print('Already Connected.')
print('Network Settings:', sta_if.ifconfig())
```
When that is completed and the microcontroller is correctly connected to the WiFi, we can connect it to AdaFruit IO, so we can visualize our result in the dashboard. This is done by the code below.
```javascript=35
AIO_SERVER = 'io.adafruit.com'
AIO_PORT = 1883
AIO_USER = 'USERNAME'
AIO_KEY = 'USER KEY'
AIO_CONTROL_FEED = 'CHOSEN FEED'
AIO_CLIENT_ID = ubinascii.hexlify(machine.unique_id()) # Can be anything
client = MQTTClient(AIO_CLIENT_ID, AIO_SERVER, AIO_PORT, AIO_USER, AIO_KEY)
client.connect()
print('Connected to AdaFruit feed!')
```
The only thing left is to gain the result from the sensor and upload it to AdaFruit with the interval of 10 seconds! This is done by the next code snippet.
```javascript=46
# Initialize the soil sensor on A0.
soilsensor =ADC(0)
# The last_message variable will hold the last time a message was sent.
# The message_interval is the time between the message, set to 2 minutes (60 * 10 seconds).
last_message = 0
message_interval = 10
# Function to read the soil moisture sensor.
def moist_sensor():
soil = soilsensor.read()
return soil
while True:
try:
if (time.time() - last_message) > message_interval:
# Get readings.
soil = moist_sensor()
# Print readings to serial.
print(soil)
# Publish readings to topics.
client.publish(AIO_CONTROL_FEED, str(soil))
# Update the time when the last readings was sent.
last_message = time.time()
except OSError as e:
restart_and_reconnect()
```
That is all the code needed for this to properly work!
## Transmitting the Data
The clever thing about the ESP8266 NodeMCU V3 is that it has WiFi, and that is the chosen protocol to send information. If one would want to make this project portable with a battery, an option would be to instead use a device with other wireless protocols (like the LoPy4 which have LoRa and SigFox) as WiFi has a shorter range and higher power consumption. It still is perfectly usable as it is now for home use!
The MQTT broker used, as mentioned before, is AdaFruit IO. I chose to make the device send information to the dashboard every 10 seconds, only to see quick differences. For future projects, it would be more suited for a much longer wait time between sendings, as you don't need the information that quick as I put it.
## Presenting the data
### Create the dashboard
Before you can present the data, there are some things you need to fix. The first thing needed is the feed you are going to send to. This is done by going the the "Feed" tab, click on "New Feed", and then choose the correct settings.

When that is done, you can head on over to the dashboard settings. Here you want to create a new dashboard, with the correct settings depending on your project. When you are in the dashboard, you need to create a new block. This is done by clicking on the cogwheel, and choosing "Create New Block" seen in the picture below.

For this kind of project, a Gauge meter is suitable to use. You can find it in the picture given below.

When you select the Gauge block, you have some settings you need to set, the most important being the correct feed. You will get a list with your feeds, choose the correct one. After that you have to choose which values the gauge will work on, I chose 0-1024, as it is the max value readable. When that is done, you just import and viola! Your finished dashboard!
Now just run the app in Thonny and watch as the magic happens, and see as the result change (usually every 10 seconds)! Example result shown below.

Note that the higher the number is, the more dry the soil is, and vice versa.
## Final Result
Below is the picture of the final product checking the soils moisture level of a nice plant!

Some final thoughts about the project? It was fun!
I had some difficulties getting used to MicroPython, but when I got the hang of it it worked our well. Some further development would firstly to make a case for it, so it doesn't have any cables flying around and being in the way, as well for extra protection for the sensor and the controller. You could also develop this the sensor more things, such as air humidity and sun light, or even make a automatic watering station.
For me I just wish I had started sooner, or not have had such I tight schedule during the summer, as it was very time consuming to learn everything needed as well as doing a lot of troubleshooting, but it was a fun way of pushing myself to the end!