By Henrik Andreasson Hallstensson ha223sp
My name is **Henrik** 👱♂️.
My mothers name is **Karin** 👩.
Karin likes to grow stuff in her greenhouse 🥗.
I like learning new things 👨🎓.
So i decided to make her greenhouse alittle bit smarter 💡.
**Time to complete:** 8-10 hours.
**View code here:**
https://github.com/Hennrikandreassonha/GreenhouseProject
**View project video here:**
https://www.youtube.com/watch?v=x9jaxa72BEo&ab_channel=doomscroller955
## **Objective**
My mother has a big interest in gardening. She has recently purchased a greenhouse in which she will grow tomatoes, cucumber, sallad, beans and so on.
In a greenhouse it is important have the right conditions to make your tomatoes grow as big as possible! Some of these conditions include: temperature, humidity, light and soilmoisture.
So i thought these parameters would make a good IoT project.
### **Main features**
* Real time updates which you can see in your smartphone.
* LCD-screen which will be mounted in the greenhouse. This will update in realtime, making it easy to see for example the soilmoisture while you are watering the plants.
* Automatic email updates from the day at 18.00 everyday. The update will show what the values were at 03.00, 12.00 and 18.00. This will be an easy way to spot if there was -degrees during the night.
I think completing these objectives will give me a deeper insight in IoT, sensors and electronic components.
### **Material**
| Supplier | Product | Cost | Specification |
| ---------- | ---------------------------------------- | ------- | --------------------------- |
| Electrokit | Adafruit STEMMA Soil Sensor | 115 sek | Soil moisture sensor |
| Electrokit | LCD 2×16 JHD162A STN blå/vit LED | 99 sek | LCD screen |
| Electrokit | I2C interface for LCD | 39 sek | I2C for LCD |
| Electrokit | TSL2591 Digital light sensor breakout | 109 sek | Lightsensor |
| Biltema | Powerpack, 2000 mAh | 40 kr | Powerbank for power |
| Electrokit | Digital temperatur- och fuktsensor DHT11 | 49 kr | Temperatue and humid sensor |
|Total| |451 kr| |
I choose **Adafruit** **STEMMA Soil Sensor** since i think it was awesome looking easy to use and implement.
The reason why i choose to use an **I2C** interface for LCD is that it makes the whole process of using a LCD alot easier. All you have to do is connect the four pins instead of 16. This will save you alot of spots on your pico and you dont have to use as much wire. Keep in mind that mounting the I2C to LCD requires some soldering.
At first i thought of using the analog light sensor that was included in the starterkit. I later changed my mind and wanted a digital one and picked the TSL2591. I also thought it had a little better look than the analog one.
### **Optional**
For running TIG stack
| Supplier | Product | Cost | Specification |
| -------------- | ----------------- | ------- | ------------------------------------------------ |
| RaspberryPi.dk | Raspberry Pi | 800 sek | Raspberry Pi 4 model B 2gb |
| RaspberryPi.dk | Raspberry Pi Case | 100 sek | Official Raspberry Pi 4 B Case – Red/White |
| RaspberryPi.dk | Power Supply | 140 sek | Official Raspberry Pi USB-C Power Supply – 5V 3A |
| Total | |1040 sek| |
It does not have to be a Raspberry Pi 4. It can be any older or newer version.
I also liked the look of the Red/White case and it provides a good protection from dust.
If you are going to run your tig stack it is important to also include power supply for the Raspberry!
**Powering the Pico**
My first thought was to purchase some batterypack that is made for powering electric stuff like Pico. For example

Later on i decided to go with a powerbank since it is easy to recharge and outputs a voltage of 5V. (Picos safe operating voltages are between 1.8V and 5.5V)
## Computer setup
I decided to use Visual Code since im used to it and i enjoy the look of it. I also tried Thonny but figured id use Visual Code since i was already familiar with it.
Programming the Pico is done using MicroPython. MicroPython is a software implementation of the Python programming language designed for microcontrollers and embedded systems.
Pairing and uploading code to Pico is done using an extension called PyMakr
To install PyMakr open VsCode and click extensions

Then search PyMakr
Your Pico should then show up in PyMakr tab where you click connect.

### Saving code
To save my code i am using Github. I would recommend you to also use it since its widely used in the tech industry and alot of companies are using it.
It is also convenient to be able to reach your code on two pcs without having to use a usb or external hard drive. I do most of my programming on a stationary workstation and use my laptop for testing at the greenhouse location.
## Putting everything together
In this picture you can see sensors and LED. Notice that the Soilmoisture sensor connections has been extended to 1 meter. Pico will be placed on a shelf where it wil be protected from water while the sensor will be placed in the soil.
This wiring is not very good, in the future i would like to make it more clean with tight wires. The setup right now makes it quite hard to change wires and seeing where the wire goes from the sensor is almost impossible!

**Soldering**
I would recommend you to have a good and up to date solderingstation. I tried soldering with an old soldering pen which was not successful. This on the other hand was pure fun. Having a good setup will save you alot of time, frustration (and in my case, money).

### Circuit diagram
The follow schematic has been drawn using Fritzing. It is a really simple and easy way of drawing schematics.
Notice that the green wires coming from Pin nr one is the SDA connection and the yellow one is the SCL. The sensors and LCD are then connected to the I2C left of the Pico. The DHT11 sensor is sending data into pin number nine.
The **LCD** screen is connected to the 5v output, I tried connecting it to the 3.3V breadboard first. It then started but did not show any screen output.
After some troubleshooting i tried the 5V and it turns out it needs 5V to operate properly. At first i thought it was my soldering that was done inproperly but it runs on 4.7V - 5.3V.
(Better check what voltage it runs on next time)

**Tip**: if you do not find the correct components you can easily download it and drag and drop it into the program.
For example rasberry.pi has the schematics for the Pico.
https://www.raspberrypi.com/documentation/microcontrollers/raspberry-pi-pico.html
Download this and simply drag and drop it into the Fritzing program.

## Platform
I choose the Tig stack since i wanted a Self hosted IoT solution. I did not want to use Node-Red since i have already used it before. I also liked the look of Grafana and the customization that was available.
Telegraf, InfluxDB, and Grafana are three software tools commonly used together in the field of monitoring and visualization.
The Mqtt broker Adafruit was chosen since the univeristy had a tutorial and once i tried it, it worked flawlessly and i had no point in changing to another one.
**Adafruit** is a free mqtt broker that can also be used to display your data. In my case im just justing it for the mqtt broker.
**InfluxDB** is a database that is made for storing all types of time series data and this fits my IoT project.
**Grafana** is used to make custom grafs to present your data.
Grafana has various panels that displays data that you can choose from. For example i am using a Gauge to present the soil moisture.
#### Running TIG stack
Since i wanted to be able to view the values of the greenhouse from anywhere in my phone localhost was not an option. I needed somewhere to run the Tig stack. My solution to this was to purchase a Raspberry PI 4, run the tig-stack there and then use port forwarding to view it from outside of local network.
This is optional and is not required. I think Raspberry Pi´s are awesome and i wanted one anyway!
Keep in mind that you would need some kind of computer and some kind of hosting if you want to be able to view your stats from anywhere!
#### **Picture of Raspberry Pi running the Tig stack**

## The Code
### Defining sensors and reading data
As you can see most of the sensors are using the I2C protocol except the DHT11 which is a digital sensor.
Declaring sensors are pretty much straight forward. The only thing that is different is the LCD 2x16. This takes 4 arguments, i2c, address, number of rows and number of columns.

### Sending email updates.
Each day at 18.00 the program sends an email which contains a summary of the day.
At 03.00, 12.00 and 18.00 the values are saved and later sent in the summary.
It is dangerous for the plants if the temperature drops too low and this will give my mother a headsup thats its getting too cold during the night.
The sent email are shown in the Presenting Data section.
Starting out with email updates we need to set the time right.
I used a library called ntptime to set the correct date and time. This is done in the boot file.

When the time is set correctly we can use it to send emails. Notice that we are adding 2 hours to the variable hour to compensate for time zone difference.


As you can see in this codesnippet we are making a check to see if the email has already been sent. This is done by checking which day it is. Since we are only sending one email every day it works great.
When the hour is eight and no email has been sent, the day will be set to current day and this will stop the Pico from sending another mail in next loop.
If we didnt complete this check an email would be sent in every loop when the hour is 18.
This would cause an intense amount of spam!
This is the email which will be recieved. It contains some HTML since i thought it looked good. You can find this HTML code in the SendEmail file which is located in lib folder.
For sending emails i am using a library called **Umail**.
It is a library that is used to send emails from microcontrollers.
You can use it with for example a google email.
Beware that you have to create an "app-password". This is done in your Google account in the security tab.
#### A snippet for the Email code:
Using inline style css since its working better with the Iphone email app.

### Displaying values in the LCD screen
The program sends updates every 15 seconds and i decided to put the screen change function inside the main loop. This means two different values will be shown every 15 seconds. At first i thought i might show them five seconds each but it turns out it was changing too often.
To achieve this function if used two If-statements and a simple bool that changes value every loop.
I have also included a function that changes the state of the backlight. If the clock is past 9 in the evening or less than 9 in the morning, it turns off the light on the display. The reason behind this is that i do not want keep the display on over night.
### The following code snippet is handling the LCD functions.
Loop one displaying Soil moisture and Brightness.
Loop number two displaying Temperature and Humidity.

#### Code for checking if light should be on or off.

#### Error handling
The last bit of code i thought i might show is about error handling and it is an important bit.
If there is any error in the main loop, for example: disconnects or input-output error the pico will reboot. If we did not have this try-catch block, the pico would stop sending readings and you would have to reboot it manually.

## Transmitting the data / connectivity
The data is being sent using Wifi and it is sent every 15 seconds.
LORaWan was not an option since it isnt available at the greenhouse location. I would have chosen wifi anyway since it was already covering the greenhouse.
I am using the Mqtt protocol.
First we are subscribing to our readings in Adafruit using **Telegraf**.
This is done in the Telegraf config file.
#### Example of subscribing to a feed in Adafruit

These readings are then saved in InfluxDB and Grafana is reading the values from it. It is important to have a database if you want to view history of readings, and this is a key point in this project.
To enable access to the Grafana website from anywhere, I am utilizing port forwarding.
Port forwarding takes your local website and puts it on the world wide web.
At first i tried using a service called Ngrok which provides an easy way of putting your website on the internet. I had some problems with this tho.
The problem was if the site was idle for than two hours it would go offline and i would have to relaunch the site from my pc again.
After some research i later decided to host it on my own through my router and it worked out great and it stays online.
Port forwarding are built in into most routers and is easy to setup. There are several guides online.
## Presenting the data
Displaying the data is done using Grafana, email and LCD. I really like the customizability and all the features that are available Grafana.
The data is saved every 15 seconds.
### Panel number one, overview
This is the top panel that is showing when you are viewing Grafana. The point of this is to give the user a fast and very readable overview of the values in the greenhouse.
Sometimes it might be hard to remember what values you should strive for in the greenhouse and this is the reason why I have decided to include an overview of the optimal values. These are displayed at the bottom in the table and are hardcoded.

To implement the optimal values text I have used the visualisation "Text" which can be found in the Visualisations tab. In the Text visualisation you can insert markdown or HTML to make it apear like in my case as a table.


### Panel number two, graph panels
Panel number two is meant to give the user a longterm overview of the past values. For example it is great to be able to see how long the soil will be humid if you have watered in the morning. Or maybe you would like to see how warm the greenhouse was a particular day.
I have also included different thresholds. This gives the user an easier time keeping the values within the optimal ranges.

### Email updates
The email updates are also a way of presenting data and it is done **automatically** every day at 18.00. This give a clear view of the values during the night and day.
#### The following picture displays the look of the update email

#### Presenting data in LCD
When you are out working in the greenhouse it is nice to quickly be able to see for example the soilmoisture. Do you need to water some more or is it enough? With a LCD screen you can quickly see if your soil have had enough.
These two texts will shift every 15 second secons.
#### The following picture is the LCD mounted in greenhouse.
It is not the greatest looking frame but it gives alittle bit of shade which makes it easier to read the values and it looks better than without a frame!
These 2 rows are displaying temperature and humidity.

#### Showing the other two values, soilmoisture and light

# Final thoughts
In a future update i might add a better casing for the Pico, this would protect it moisture, dirt and water. A greenhouse is quite a harsh enviorment for electronic components.
One thought I had was to install it on the underside of the shelf in the greenhouse instead of on the top. This alternative placement is might be better because there may be a risk of condensation causing drips on the top of the shelf.
It would also protect it from the sun since direct sun on the temperature sensor would cause faulty readings.
Another improvement would be better protected wiring since it is really exposed to water down in the soil.
The red line is the underside of shelf where I would put the Pico. I would do this using zipties or screws.
Video link:
https://www.youtube.com/watch?v=x9jaxa72BEo&ab_channel=doomscroller955
#### Karin with her new improved greenhouse
