Users Online

· Guests Online: 22

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

#01_01 A Simple Smart Gardening System

A Simple Smart Gardening System

 

Gardening is a nice activity. It needs care to keep a crop growing well. It is not possible to monitor and tend to a garden 24 hours a day, so we need a smart gardening system that can monitor and tend to the garden as we want it. This chapter will help you explore existing gardening systems and build your own simple smart gardening system.

In this chapter, we will cover the following topics:

  • Introducing smart gardening systems

  • Exploring gardening system platforms

  • Watering your garden and farm

  • Sensor devices for a smart gardening system

  • Watering your garden and farm

  • Building a smart gardening system

Let's get started!

 

Introducing smart gardening system

 

A gardening system is a system used to practice growing and cultivating plants as a part of horticulture. A gardening system is usually developed and implemented as a manual operation. An automated gardening system is designed to enable us to manage gardening, including monitoring moisture, temperature, and humidity.

In general, we can build a smart gardening system based on the high-level architecture that is shown in the following figure:



The following is a list of components to build a smart gardening system:

  • Sensors: Corresponding to your case, you need sensor devices to measure the garden's environment and condition. Capturing physical objects to digital form enables us to perform computing and processing.

  • MCU board with network module: The goal of MCU is to process all data that is acquired from sensors. Most MCU boards have limited computation, so we need to send sensor data to a server for further computation. To enable us to send data, the MCU board should be attached to a network module, either Ethernet or wireless.

  • Gateway: This is optional since some MCU boards can communicate with a server directly without modifying the protocol format. If a network module has the capability to deliver data over a primitive protocol, the functioning of gateway is necessary because a gateway can translate one protocol format to another protocol format.

  • Server: This is a center computation. Most servers have high-end hardware so heavy computation can be addressed.

This architecture is an ideal condition. In a real project, you may integrate an MCU board and server in one box. For instance, you can use a Raspberry Pi or BeagleBoard. These are a mini computers that you can deploy libraries to with respect to your case.

 

Exploring gardening system platforms

 

In this section, we will explore some gardening systems that could be used with our board, such as Arduino and Raspberry Pi. Some manufacturers provide kits that you can use directly in your project.

We will review three gardening system platforms that you may fit with your case.

 

Open Garden shield for Arduino

 

Open Garden shield for Arduino is manufactured by Cooking Hacks. This shield provides I/O connectors for gardening and farming sensors. It also includes an RF module with 433 MHz frequency. For further information about this shield, you can visit the official website at https://www.cooking-hacks.com/open-garden-shield-for-arduino. You can see this shield here:



Cooking Hacks provides a complete kit that you can use with Arduino directly. Currently, there are three kits. Each kit has unique features, including sensors and tools. The following is a list of Open Garden kits:

You can see a sample Open Garden kit for indoor use here:



 

Grove Smart Plant Care kit for Arduino

 

SeeedStudio has popular products called Grove. It makes it easier for you to connect your board to various sensor and actuator devices. Currently, SeeedStudio provides the Grove Smart Plant kit for Arduino. This kit consists of temperature, humidity, soil moisture, and illumination intensity sensors. To connect these sensors, the kit provides a Grove Base shield that you can attach to Arduino.

You can buy this kit on the official website, https://www.seeedstudio.com/Grove-Smart-Plant-Care-Kit-for-Arduino-p-2528.html. One type of Grove smart plant care kit for Arduino is shown here:



 

EcoDuino

 

EcoDuino is a gardening kit from DFRobot. This kit consists of an MCU board and sensors. The board also provides an RF module breakout in an XBee breakout model. It enables the board to communicate with other platforms. The kit comes with soil moisture, temperature, and humidity (DHT11) sensors. If you're interested in this kit, you can buy it from this website: https://www.dfrobot.com/product-641.html.

The EcoDuino kit is shown in the following image:



 

Sensor devices for a smart gardening system

 

To build a smart gardening system, we need some sensors related to gardening and farming. In this section, we will review the main sensors that are used in gardening and farming. Soil moisture, temperature, and humidity are three parameters that we can use to build our smart gardening system.

Let's explore!

 

Soil moisture sensor

 

One of the parameters of gardening is soil moisture. We should measure soil moisture to ensure our plant grows well. There are many options when it comes to soil moisture sensors. You can use the SparkFun Soil Moisture Sensor, for example. You can find this module at https://www.sparkfun.com/products/13322 .

You can see the SparkFun Soil Moisture Sensor in the following image:



You can use other soil moisture sensors from cheap manufacturers in China. You can order them from Alibaba or Aliexpress.

To read soil moisture values, we can use analog I/O. To use analog I/O, you should be familiar with the following Sketch APIs:

  • analogRead() is for reading analog data from an analog pin on Arduino

  • analogWrite() is for writing analog data to an analog pin on Arduino

For demonstration, we'll connect an Arduino board to the SparkFun Soil Moisture sensor. The following is the wiring used:

  • VCC is connected to 5V on the Arduino

  • GND is connected to GND on the Arduino

  • SIG is connected to A0 on the Arduino

A complete wiring can be seen in the following figure:



Now you can open the Arduino software. If you haven't installed it yet, you can download and install the tool from https://www.arduino.cc. Once done, you can write a Sketch program. Create this script:

void setup() { 

Serial.begin(9600); 





void loop() { 

int val; 

val = analogRead(A0); 



Serial.print("Soil moisture: "); 

Serial.print(val); 



delay(3000); 




The program starts by initializing a Serial object with a baud rate of 9600. In a looping program, we read soil moisture levels using the analogRead() method. Then the measurement is printed to the serial port.

Save this Sketch file and upload the program to the Arduino board. To see the output data, you can use the serial monitor in the Arduino software. You can find it by going to Tools | Serial Monitor. You should see a soil moisture reading in the Serial Monitor tool.

 

Temperature and humidity sensor

 

Temperature and humidity have significant impact on the growth of the crop. Keeping temperature and humidity within certain values also keeps crops healthy. To monitor temperature and humidity, we can use the DHT22 or DHT11 for Arduino and Raspberry Pi. These sensors, DHT22 and DHT11, are famous sensors and have a lot of resources available for development.

The RHT03 (also known as DHT22) is a low-cost humidity and temperature sensor with a single-wire digital interface. You can obtain this module from SparkFun (https://www.sparkfun.com/products/10167) and Adafruit (https://www.adafruit.com/products/393). You may also find it in your local online or electronics store.

You can see the DHT22 module in the following figure:



Source: https://www.adafruit.com/products/385

For further information about the DHT22 module, you can read the DHT22 datasheet at http://cdn.sparkfun.com/datasheets/Sensors/Weather/RHT03.pdf.

Now we connect the DHT22 module to the Arduino. The following is the wiring:

  • VDD (pin 1) is connected to the 3.3V pin on the Arduino

  • SIG (pin 2) is connected to digital pin 8 on the Arduino

  • GND (pin 4) is connected to GND on the Arduino

You can see the complete wiring in the following figure:



To access the DHT-22 on the Arduino, we can use the DHT sensor library from Adafruit: https://github.com/adafruit/DHT-sensor-library. We can install this library from the Arduino software. Go to Sketch | Include Library | Manage Libraries and you will get a dialog.

Search for dht in Library Manager. You should see the DHT sensor library by Adafruit. Install this library:



Now let's start to write our Sketch program. You can develop a Sketch program to read temperature and humidity using DHT22. You can write this Sketch program in the Arduino software:

#include "DHT.h" 



// define DHT22 

#define DHTTYPE DHT22 

// define pin on DHT22 

#define DHTPIN 8 



DHT dht(DHTPIN, DHTTYPE); 



void setup() { 

Serial.begin(9600); 

dht.begin(); 





void loop() { 

delay(2000); 



// Reading temperature or humidity takes about 250 milliseconds! 

// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) 

float h = dht.readHumidity(); 

// Read temperature as Celsius (the default) 

float t = dht.readTemperature(); 





// Check if any reads failed and exit early (to try again). 

if (isnan(h) || isnan(t)) { 

Serial.println("Failed to read from DHT sensor!"); 

return; 





// Compute heat index in Celsius (isFahreheit = false) 

float hic = dht.computeHeatIndex(t, h, false); 



Serial.print("Humidity: "); 

Serial.print(h); 

Serial.print(" %\t"); 

Serial.print("Temperature: "); 

Serial.print(t); 

Serial.print(" *C\t"); 

Serial.print("Heat index: "); 

Serial.print(hic); 

Serial.println(" *C "); 




Save the program. Now you can compile and upload it to the Arduino board. Furthermore, you can open Serial Monitor to see sensor data from the serial port. You can see a sample program output in the following screenshot:



How it works

In the setup() function, we initialize the DHT module by calling dht.begin(). To read temperature and humidity, you can use dht.readTemperature() and dht.readHumidity(). You also can get a heat index using the dht.computeHeatIndex() function.

 

Watering your garden and farm

 

One of the problems in gardening systems is how to water our garden or farm. There are pumps that fit boards such as the Arduino and Raspberry Pi. The 350GPH liquid pump (https://www.sparkfun.com/products/10455) could be used on your Arduino or Raspberry Pi:



You can also use a higher-voltage pump. To control it from the Arduino, you can use a relay that is connected between the Arduino and the pump. A relay can be connected to digital pins from Arduino. Using  digitalRead() and digitalWrite() we can communicate with Relay from Arduino.

 

Building a smart gardening system

 

In this section, we will develop a smart gardening system. We will use a PID controller to manage all inputs from our sensors, which will be used in decision system. We'll measure soil moisture, temperature, and humidity as parameters for our system. To keep it simple for now, we'll only use one parameter, soil moisture level.

A high-level architecture can be seen in the following figure:



You can replace the MCU board and computer with a mini computer such as a Raspberry Pi. If you use a Raspberry Pi, you should remember that it does not have an analog input pin so you need an additional chip ADC, for instance the MCP3008, to work with analog input.

Assuming the watering system is connected via a relay, if we want to water the garden or farm, we just send digital value 1 to a relay. Some designs use a motor.

Let's build!

 

Introducing the PID controller

 

Proportional-integral-derivative (PID) control is the most common control algorithm used in the industry and has been universally accepted in industrial control. The basic idea behind a PID controller is to read a sensor and then compute the desired actuator output by calculating proportional, integral, and derivative responses and summing those three components to compute the output. The design of a general PID controller is as follows:



Furthermore, a PID controller formula can be defined as follows:

 represents the coefficients for the proportional, integral, and derivative. These parameters are non-negative values. The variable  represents the tracking error, the difference between the desired input value i and the actual output y. This error signal  will be sent to the PID controller.

 

Implementing a PID controller in Python

 

In this section, we'll build a Python application to implement a PID controller. In general, our program flowchart can be described as follows:



We should not build a PID library from scratch. You can translate the PID controller formula into Python code easily. For implementation, I'm using the PID class from https://github.com/ivmech/ivPID. The following the PID.py file:

import time 



class PID: 

"""PID Controller 

""" 



def __init__(self, P=0.2, I=0.0, D=0.0): 



self.Kp = P 

self.Ki = I 

self.Kd = D 



self.sample_time = 0.00 

self.current_time = time.time() 

self.last_time = self.current_time 



self.clear() 



def clear(self): 

"""Clears PID computations and coefficients""" 

self.SetPoint = 0.0 



self.PTerm = 0.0 

self.ITerm = 0.0 

self.DTerm = 0.0 

self.last_error = 0.0 



# Windup Guard 

self.int_error = 0.0 

self.windup_guard = 20.0 



self.output = 0.0 



def update(self, feedback_value): 

"""Calculates PID value for given reference feedback 



.. math:: 

u(t) = K_p e(t) + K_i \int_{0}^{t} e(t)dt + K_d {de}/{dt} 



.. figure:: images/pid_1.png 

:align: center 



Test PID with Kp=1.2, Ki=1, Kd=0.001 (test_pid.py) 



"" 

error = self.SetPoint - feedback_value 



self.current_time = time.time() 

delta_time = self.current_time - self.last_time 

delta_error = error - self.last_error 



if (delta_time >= self.sample_time): 

self.PTerm = self.Kp * error 

self.ITerm += error * delta_time 



if (self.ITerm < -self.windup_guard): 

self.ITerm = -self.windup_guard 

elif (self.ITerm > self.windup_guard): 

self.ITerm = self.windup_guard 



self.DTerm = 0.0 

if delta_time > 0: 

self.DTerm = delta_error / delta_time 



# Remember last time and last error for next calculation 

self.last_time = self.current_time 

self.last_error = error 



self.output = self.PTerm + (self.Ki * self.ITerm) + (self.Kd * self.DTerm) 



def setKp(self, proportional_gain): 

"""Determines how aggressively the PID reacts to the current error with setting Proportional Gain""" 

self.Kp = proportional_gain 



def setKi(self, integral_gain): 

"""Determines how aggressively the PID reacts to the current error with setting Integral Gain""" 

self.Ki = integral_gain 



def setKd(self, derivative_gain): 

"""Determines how aggressively the PID reacts to the current error with setting Derivative Gain""" 

self.Kd = derivative_gain 



def setWindup(self, windup): 

"""Integral windup, also known as integrator windup or reset windup, 

refers to the situation in a PID feedback controller where 

a large change in setpoint occurs (say a positive change) 

and the integral terms accumulates a significant error during the rise (windup), thus overshooting and continuing 

to increase as this accumulated error is unwound 

(offset by errors in the other direction). 

The specific problem is the excess overshooting. 

""" 

self.windup_guard = windup 



def setSampleTime(self, sample_time): 

"""PID that should be updated at a regular interval. 

Based on a pre-determined sample time, the PID decides if it should compute or return immediately. 

""" 

self.sample_time = sample_time 


For testing, we'll create a simple program for simulation. We need libraries such as numpyscipypandaspatsy, and matplotlib. Firstly, you should install python-dev for Python development. Type these commands on a Raspberry Pi terminal:


$ sudo apt-get update


$ sudo apt-get install python-dev



Now you can install the numpyscipypandas, and patsy libraries. Open a Raspberry Pi terminal and type these commands:


$ sudo apt-get install python-scipy


$ pip install numpy scipy pandas patsy



The last step is to install the matplotlib library from the source code. Type these commands into the Raspberry Pi terminal:


$ git clone https://github.com/matplotlib/matplotlib


$ cd matplotlib


$ python setup.py build


$ sudo python setup.py install



After the required libraries are installed, we can test our PID.py code. Create a script with the following contents:

import matplotlib 

matplotlib.use('Agg') 



import PID 

import time 

import matplotlib.pyplot as plt 

import numpy as np 

from scipy.interpolate import spline 





P = 1.4 

I = 1 

D = 0.001 

pid = PID.PID(P, I, D) 



pid.SetPoint = 0.0 

pid.setSampleTime(0.01) 



total_sampling = 100 

feedback = 0 



feedback_list = [] 

time_list = [] 

setpoint_list = [] 



print("simulating....") 

for i in range(1, total_sampling): 

pid.update(feedback) 

output = pid.output 

if pid.SetPoint > 0: 

feedback += (output - (1 / i)) 



if 20 < i < 60: 

pid.SetPoint = 1 



if 60 <= i < 80: 

pid.SetPoint = 0.5 



if i >= 80: 

pid.SetPoint = 1.3 



time.sleep(0.02) 



feedback_list.append(feedback) 

setpoint_list.append(pid.SetPoint) 

time_list.append(i) 



time_sm = np.array(time_list) 

time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300) 

feedback_smooth = spline(time_list, feedback_list, time_smooth) 



fig1 = plt.gcf() 

fig1.subplots_adjust(bottom=0.15) 



plt.plot(time_smooth, feedback_smooth, color='red') 

plt.plot(time_list, setpoint_list, color='blue') 

plt.xlim((0, total_sampling)) 

plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5)) 

plt.xlabel('time (s)') 

plt.ylabel('PID (PV)') 

plt.title('TEST PID') 





plt.grid(True) 

print("saving...") 

fig1.savefig('result.png', dpi=100) 


Save this program into a file called test_pid.py. Then run it:


$ python test_pid.py



This program will generate result.png as a result of the PID process. A sample output is shown in the following screenshot. You can see that the blue line has the desired values and the red line is the output of the PID:



 

How it works

 

First, we define our PID parameters:

P = 1.4 

I = 1 

D = 0.001 

pid = PID.PID(P, I, D) 



pid.SetPoint = 0.0 

pid.setSampleTime(0.01) 



total_sampling = 100 

feedback = 0 



feedback_list = [] 

time_list = [] 

setpoint_list = [] 


After that, we compute the PID value during sampling. In this case, we set the desired output values as follows:

  • Output 1 for sampling from 20 to 60

  • Output 0.5 for sampling from 60 to 80

  • Output 1.3 for sampling more than 80

for i in range(1, total_sampling): 

pid.update(feedback) 

output = pid.output 

if pid.SetPoint > 0: 

feedback += (output - (1 / i)) 



if 20 < i < 60: 

pid.SetPoint = 1 



if 60 <= i < 80: 

pid.SetPoint = 0.5 



if i >= 80: 

pid.SetPoint = 1.3 



time.sleep(0.02) 



feedback_list.append(feedback) 

setpoint_list.append(pid.SetPoint) 

time_list.append(i) 


The last step is to generate a report and save it into a file called result.png:

time_sm = np.array(time_list) 

time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300) 

feedback_smooth = spline(time_list, feedback_list, time_smooth) 



fig1 = plt.gcf() 

fig1.subplots_adjust(bottom=0.15) 



plt.plot(time_smooth, feedback_smooth, color='red') 

plt.plot(time_list, setpoint_list, color='blue') 

plt.xlim((0, total_sampling)) 

plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5)) 

plt.xlabel('time (s)') 

plt.ylabel('PID (PV)') 

plt.title('TEST PID') 





plt.grid(True) 

print("saving...") 

fig1.savefig('result.png', dpi=100) 


 

Sending data from the Arduino to the server

 

Not all Arduino boards have the capability to communicate with a server. Some Arduino models have built-in Wi-Fi that can connect and send data to a server, for instance, the Arduino Yun, Arduino MKR1000, and Arduino UNO Wi-Fi.

You can use the HTTP or MQTT protocols to communicate with the server. After the server receives the data, it will perform a computation to determine its decision.

 

Controlling soil moisture using a PID controller

 

Now we can change our PID controller simulation using a real application. We use soil moisture to decide whether to pump water. The output of the measurement is used as feedback input for the PID controller.

If the PID output is a positive value, then we turn on the watering system. Otherwise, we stop it. This may not be a good approach but is a good way to show how PID controllers work. Soil moisture data is obtained from the Arduino through a wireless network.

Let's write this program:

import matplotlib 

matplotlib.use('Agg') 



import PID 

import time 

import matplotlib.pyplot as plt 

import numpy as np 

from scipy.interpolate import spline 



P = 1.4 

I = 1 

D = 0.001 

pid = PID.PID(P, I, D) 



pid.SetPoint = 0.0 

pid.setSampleTime(0.25) # a second 



total_sampling = 100 

sampling_i = 0 

measurement = 0 

feedback = 0 



feedback_list = [] 

time_list = [] 

setpoint_list = [] 





def get_soil_moisture(): 

# reading from Arduino 

# value 0 - 1023 

return 200 







print('PID controller is running..') 

try: 

while 1: 

pid.update(feedback) 

output = pid.output 



soil_moisture = get_soil_moisture() 

if soil_moisture is not None: 



# # ## testing 

# if 23 < sampling_i < 50: 

# soil_moisture = 300 



# if 65 <= sampling_i < 75: 

# soil_moisture = 350 



# if sampling_i >= 85: 

# soil_moisture = 250 

# # ################ 



if pid.SetPoint > 0: 

feedback += soil_moisture + output 



print('i={0} desired.soil_moisture={1:0.1f} soil_moisture={2:0.1f} pid.out={3:0.1f} feedback={4:0.1f}' 

.format(sampling_i, pid.SetPoint, soil_moisture, output, feedback)) 

if output > 0: 

print('turn on watering system') 

elif output < 0: 

print('turn off watering system') 



if 20 < sampling_i < 60: 

pid.SetPoint = 300 # soil_moisture 



if 60 <= sampling_i < 80: 

pid.SetPoint = 200 # soil_moisture 



if sampling_i >= 80: 

pid.SetPoint = 260 # soil_moisture 







time.sleep(0.5) 

sampling_i += 1 



feedback_list.append(feedback) 

setpoint_list.append(pid.SetPoint) 

time_list.append(sampling_i) 



if sampling_i >= total_sampling: 

break 



except KeyboardInterrupt: 

print("exit") 





print("pid controller done.") 

print("generating a report...") 

time_sm = np.array(time_list) 

time_smooth = np.linspace(time_sm.min(), time_sm.max(), 300) 

feedback_smooth = spline(time_list, feedback_list, time_smooth) 



fig1 = plt.gcf() 

fig1.subplots_adjust(bottom=0.15, left=0.1) 



plt.plot(time_smooth, feedback_smooth, color='red') 

plt.plot(time_list, setpoint_list, color='blue') 

plt.xlim((0, total_sampling)) 

plt.ylim((min(feedback_list) - 0.5, max(feedback_list) + 0.5)) 

plt.xlabel('time (s)') 

plt.ylabel('PID (PV)') 

plt.title('Soil Moisture PID Controller') 





plt.grid(True) 

fig1.savefig('pid_soil_moisture.png', dpi=100) 

print("finish") 


Save this program to a file called ch01_pid.py and run it like this:


$ sudo python ch01_pid.py



After executing the program, you should obtain a file called pid_soil_moisture.png. A sample output can be seen in the following figure:



 

How it works

 

Generally speaking, this program combines two things: reading the current soil moisture value through a soil moisture sensor and implementing a PID controller. After measuring the soil moisture level, we send the value to the PID controller program. The output of the PID controller will cause a certain action. In this case, it will turn on the watering machine.

 

Summary

 

We reviewed several gardening system platforms. Then we explored two sensor devices commonly used in real projects. Lastly, we built a decision system to automate for watering garden using PID. 

In the next chapter, we will explore a smart parking system and try to build a prototype.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.07 seconds
10,800,075 unique visits