Automatic Irrigation System

by DarkFLAME in Circuits > Raspberry Pi

1210 Views, 13 Favorites, 0 Comments

Automatic Irrigation System

FDWGS88LWXJXUMV.jpg

I'm a thirteen-year-old student from Salwan Public Schools, India

My Project -: Automatic Irrigation System

With the world's population on the rise and resources becoming scarcer, finding innovative solutions to improve agricultural productivity while conserving water has never been more critical. An affordable automatic irrigation system holds the promise of addressing these challenges by providing efficient and sustainable water management solutions, even for subsistence farmers in resource-constrained regions.

Addressing the Needs of a Growing Population:

As the global population continues to grow, the demand for food also increases. However, traditional farming methods often struggle to keep pace with this demand, leading to food shortages and environmental degradation. By implementing affordable automatic irrigation systems, farmers can optimize water usage and maximize crop yields, contributing to food security for communities around the world.

Empowering Subsistence Farmers:

Subsistence farmers, who rely on small plots of land for their livelihoods, often face significant challenges in accessing water for irrigation. Manual watering methods are labor-intensive and inefficient, leading to low crop yields and economic hardship. By introducing affordable automatic irrigation systems tailored to the needs and resources of subsistence farmers, we can empower them to improve their agricultural productivity, increase their incomes, and achieve greater food self-sufficiency.

Implementing Sprinkler Systems and Drip Irrigation:

Sprinkler systems and drip irrigation are two highly effective methods of automatic irrigation that can be implemented in affordable systems. Sprinkler systems deliver water through overhead sprinklers, covering large areas of land efficiently. Drip irrigation, on the other hand, delivers water directly to the roots of plants, minimizing water waste and maximizing efficiency. By combining these techniques in affordable irrigation systems, farmers can choose the most suitable method for their crops and environmental conditions, optimizing water usage and crop yields.

Supplies

20240508_213708.jpg
RPI.jpeg
Mega.jpeg

1) Raspberry Pi 4 Model B 2GB RAM (and materials required to program it)

2)Arduino Mega

3)Relay Module

4)9V Water Pump (I am Using for the miniature Model, you may use a more powerful one)

5)Pipe (depending on the area of the garden)

6)Cardboard, scissors, transparent tape, glue, etc. (If you are making a model to display in school exhibitions)

7)Soil Moisture Sensors (2)

Preparing to Create the Model's Base (Skip If You Are Planning It to Equip in Your Garden)

20240508_213925.jpg
20240508_213708.jpg

Gather Your Stuff Up!

Get some tape, cardboard, glue scissors etc. to begin the work

Step (1):

Cut the cardboard into small pieces to provide the housing for the soil to stay in. You should be able to gaze how much strips do you need to cut, depending on the size of the base you are planning to make.

Step (2):

Glue some cardboard to make the base. If you haven't got a glue gun, you might find it difficult to glue it up though you will be able to. (Tho I ran out of refills eventually so I had to glue rest of the parts. 🤣)


Compiling the Base (Skip If You Are Planning It to Equip in Your Garden)

20240508_213754.jpg

Glue the rest of the parts together and create a housing for the soil to set in. Tho this might take some time, it will stick together firmly.

Cover the base with aluminum. Don't, if want your model to become soaking wet during the exhibition.

Tape the aluminum firmly to the base.

Configuring Raspberry Pi

rpi1.jpg

Now, I will explain the use of the raspberry pi.

As we know, the pi has WiFi capabilities. Through TCP (Transfer Control Protocol), We can get the soil moisture sensor readings and pass it on to a device, (a laptop, because the android app is being made using kivyMD). Now to configure the pi, do the following:

Set Up the Operating System of the Raspberry Pi

Setting up a Raspberry Pi can be an exciting project itself! Here are the step-by-step instructions to get you started:

Step 1: Gather Your Materials

  • Raspberry Pi board (Model 4 is recommended for general use)
  • MicroSD card (at least 16GB recommended)
  • MicroSD card reader (for your computer)
  • Power supply (appropriate for your Raspberry Pi model, usually 5V 3A for Raspberry Pi 4)
  • HDMI cable (micro HDMI for Raspberry Pi 4)
  • Monitor or TV (with HDMI input)
  • Keyboard and mouse (USB or Bluetooth)
  • Internet connection (Ethernet cable or Wi-Fi)
  • Case (optional, but recommended for protection)

Step 2: Download the Operating System

  1. Download Raspberry Pi Imager from the official Raspberry Pi website: Raspberry Pi Imager
  2. Install the Raspberry Pi Imager on your computer.

Step 3: Prepare the MicroSD Card

  1. Insert the MicroSD card into your card reader and connect it to your computer.
  2. Open Raspberry Pi Imager.
  3. Select the OS:
  • Click "Choose OS" and select "Raspberry Pi OS (32-bit)" or another preferred version.
  1. Select the SD card:
  • Click "Choose SD Card" and select your inserted MicroSD card.
  1. Write the OS to the SD card:
  • Click "Write" and confirm. Wait for the process to complete.

Step 4: Set Up the Raspberry Pi

  1. Insert the MicroSD card into the Raspberry Pi.
  2. Connect the HDMI cable to your monitor/TV and the Raspberry Pi.
  3. Connect the keyboard and mouse to the Raspberry Pi.
  4. Connect the Ethernet cable (if not using Wi-Fi).
  5. Plug in the power supply to the Raspberry Pi.

Step 5: Initial Boot and Configuration

  1. Power on the monitor/TV and switch to the correct HDMI input.
  2. Plug in the Raspberry Pi power supply to power it up.
  3. Wait for the Raspberry Pi to boot. It will boot into the Raspberry Pi OS desktop.
  4. Follow the setup wizard:
  • Set up your country, language, and time zone.
  • Change the default password.
  • Connect to Wi-Fi (if using Wi-Fi).
  • Update the software (this may take some time).

Step 6: Enable SSH (Optional)

  1. Open the terminal on your Raspberry Pi.
  2. Type the following command to enable SSH:
Terminal
sudo raspi-config
  1. Navigate to Interfacing Options and select "SSH" to enable it.
  2. Finish and reboot if prompted.

Step 7: Additional Setup (Optional)

  • Install additional software:
  • Open the terminal and use sudo apt-get install <software-name> to install any additional software.
  • Set up VNC for remote desktop access:
  • Enable it through sudo raspi-config under Interfacing Options.

Step 8: Using Your Raspberry Pi

  1. Explore the pre-installed software.
  2. Start programming with Python, Scratch, or other programming tools available.
  3. Connect to the internet to browse or download more software.

Troubleshooting Tips

  • No display: Check the HDMI connection and ensure the monitor is on the correct input.
  • Power issues: Ensure you're using a compatible power supply.
  • Network issues: Verify Wi-Fi settings or check the Ethernet connection.

With these steps, your Raspberry Pi should be up and running, ready for the project

Configuring Serial Communication and TCP

FQAJ6ESLVXTXKSK.jpg

Now, the requirements are complete and hence we can proceed with setting up TCP.

Open the editor, I recommend Thonny IDE and paste the following code:

import socket

import time


from threading import Timer


import serial


# Initialize serial connection

ser = serial.Serial("/dev/ttyUSB0", 115200)

ser.flush()


# Initialize socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind(("", 5000))

s.listen(5)

print("Server is now running...")


def background_controller():

  # Read a line from the serial port

  line = ser.readline().decode("utf-8").strip()

  # Send the data to the connected client

  clientsocket.send(bytes(line, "utf-8"))

  # Set a timer to call this function again after 5 seconds

  Timer(5, background_controller).start()


# Main server loop

while True:

  print("Entered Loop...")

  # Accept a new client connection

  clientsocket, address = s.accept()

  print(f"Connection from {address} has been established....")

  # Start the background controller function

  background_controller()

Downloads

Setting Up Our Arduino Mega 2560

20240601_152944.jpg
20240601_185732.jpg
Mega.jpeg

We will connect our Arduino Mega 2560 to the raspberry pi. This will work on any Arduino board. Actually, we can continue the project without the Arduino board but for safety precaution towards the i/o pins of raspberry pi, we will use Arduino boards. So, The work of the Arduino is very simple, it will input soil moisture values, process it, and depending on the moisture threshold it will water the garden. The connection of pump, soil moisture sensor, temperature sensor and relay will be as follows. The soil moisture connection diagram can vary depending on the sensor one uses.

Now we will code the Arduino board. The code is as follows:

// Define the pin connected to the relay

#define RELAY_PIN 8

#define SMS A0

#define SMS2 A1


void setup() {

 Serial.begin(115200);

 pinMode(RELAY_PIN, OUTPUT);

 pinMode(SMS, INPUT);

 

 // Initially turn off the relay

 digitalWrite(RELAY_PIN, LOW);

}


void loop() {

 int smsValue = analogRead(SMS);

 int sms2Value = analogRead(SMS2);

 if (smsValue < 500) {

  digitalWrite(RELAY_PIN, HIGH);

 }

 else{

  digitalWrite(RELAY_PIN, LOW);

 }

 String SMSVALUE = "1," + String(smsValue);

 String SMSVALUE1 = "2," + String(sms2Value);


 Serial.println(SMSVALUE);

 delay(1000);

 Serial.println(SMSVALUE1);

 delay(1000);

}

Upload the code into your Arduino board. Connect the Arduino board to the raspberry pi using the USB cable provided with the Arduino.

Now you may attach a pipe to the pump, create holes in the pipe, and it will provide sufficient pressure to sprinkle water in the garden.

Downloads

Monitoring the System

20240601_202625.jpg

Now, I have created a program to monitor the system, I will break the functioning into the following steps:

This program requires a well-performing CPU and up to 16 GB of RAM. CPU requirement-13th Gen Intel(R) Core(TM) i5-1335U  2.30 GHz(base speed) and above. The code:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.connect(("raspberrypi", 5000))


import tkinter as tk

from tkinter import ttk

import threading

import time

import matplotlib.pyplot as plt

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

import sv_ttk



def use_data():

  while True:

    with open("data.txt", "r") as file:

      data = file.read()

      file_data = data.split()

      last_data = file_data[-1]

      sensor_number = last_data[:1]

      pseudo_sensor_value = last_data[1:]

      global sensor_value

      sensor_value = pseudo_sensor_value[1:]

      global sensor4

      if sensor_number == "1":

        sensor4.append(sensor_value)

        sensor4 = sensor4[1:]

      global sensor3 

      if sensor_number == "2":

        sensor3.append(sensor_value)

        sensor3 = sensor3[1:]


root = tk.Tk()


cf1 = ttk.LabelFrame(root, text="Data:", padding=(50, 10))

cf1.grid(row=0, column=0, padx=(20, 10), pady=(20, 10), sticky="nsew")


cf2 = ttk.LabelFrame(cf1, text="Sensor 1:", padding=(50, 10))

cf2.grid(row=0, column=0, padx=(20, 10), pady=(20, 10), sticky="nsew")


cf3 = ttk.LabelFrame(root, text="Soil Moisture Sensors:", padding=(50, 10))

cf3.grid(row=0, column=1, padx=(20, 10), pady=(20, 10), sticky="nsew")


cf4 = ttk.LabelFrame(cf1, text="Sensor 2:", padding=(50, 10))

cf4.grid(row=1, column=0, padx=(20, 10), pady=(20, 10), sticky="nsew")


label1 = ttk.Label(cf3, text="Sensor 1:")

label1.grid(row=0, column=0, padx=10, pady=10)


sv_ttk.set_theme("dark")


label2 = ttk.Label(cf3, text="Sensor 2:")

label2.grid(row=1, column=0, padx=10, pady=10)


label3 = ttk.Label(cf3, text="Sensor 3:")

label3.grid(row=2, column=0, padx=10, pady=10)


label4 = ttk.Label(cf3, text="Sensor 4:")

label4.grid(row=3, column=0, padx=10, pady=10)


sensor4 = ["0", "0", "0", "0"]

sensor4int = [0, 0, 0, 0]

time_x = [0, 0, 0, 0]

sensor3 = ["0", "0", "0", "0"]

sensor3int = [0, 0, 0, 0]

i = 0


def plotgraph4():

  for widget in cf2.winfo_children():

    widget.destroy()

  fig, ax = plt.subplots()

  ax.plot(time_x, sensor4int)

  ax.set_xlabel('Time')

  ax.set_ylabel('Sensor Value')

  ax.set_title('Soil Moisture Level, Sensor 1')

  canvas = FigureCanvasTkAgg(fig, master=cf2)

  canvas.draw()

  canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

  plt.close(fig)

  root.after(2000, plotgraph4)



def plotgraph3():

  for widget in cf4.winfo_children():

    widget.destroy()

  fig, ax = plt.subplots()

  ax.plot(time_x, sensor3int)

  ax.set_xlabel('Time')

  ax.set_ylabel('Sensor Value')

  ax.set_title('Soil Moisture Level, Sensor 2')

  canvas = FigureCanvasTkAgg(fig, master=cf4)

  canvas.draw()

  canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)

  plt.close(fig)

  root.after(2000, plotgraph3)

##def use_data():

##  while True:

##    with open("data.txt", "r") as file:

##      file_data = file.read()

##      data = file_data.split()

##      last_data = data[-1]

##      sensor_number = last_data[:1]

##      pseudo_sensor_value = last_data[1:]

##      sensor_value = pseudo_sensor_value[1:]

##      global sensor4

##      if sensor_number == "4":

##        if sensor4[-1] == sensor_value:

##          pass

##        else:

##          sensor4.append(sensor_value)

##          sensor4 = sensor4[1:]

##      elif sensor_number == "3":

##        if sensor3[-1] == sensor_value:

##          pass

##        else:

##          sensor3.append(sensor_value)

##          sensor3 = sensor3[1:]


def stopwatch():

  global time_x

  global i

  while True:

    time.sleep(1)

    i += 1

    time_x.append(i)

    time_x = time_x[1:]


def convert():

  global sensor4int, sensor4, sensor3, sensor3int

  while True:

    sensor4int = [int(val) for val in sensor4]

    sensor3int = [int(val) for val in sensor3]

    time.sleep(2)


def receive_data():

  s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

  s.connect(("raspberrypi", 5000))

   

  while True: 

    with open("data.txt", "a") as file:

      x = s.recv(1024).decode("utf-8")

      file.write(x + "\n")


threads = [

  threading.Thread(target=receive_data),

  threading.Thread(target=use_data),

  threading.Thread(target=convert),

  threading.Thread(target=stopwatch)

]


for thread in threads:

  thread.start()


plotgraph4()

plotgraph3()

root.mainloop()

You might need the following packages:

1)sv_ttk - to install, go into the command prompt and run - pip install sv_ttk

2)NumPy - pip install numpy

You might need to create a file called "data.txt" file in the same directory as your program.

You can copy the code from above and paste into the file. Or if you have a DHT 11 download this file and follow the next step.

Downloads

Configuring for Temperature Sensor (Optional)

Irrigationsolution-1536x930.jpg

If you have a temperature sensor like dht11 lying around, Instead of adding 2 soil moisture sensors, why not add a DHT11? Lets do it.

1) Attach DHT11 to the Arduino board.

2) Change the code for the dht11

The Code:



It may seem like it's the same file because of the similar name, but I have updated the code for the DHT 11. You can check the pin definitions on the code and connect accordingly. Connecting sensors is not that hard! Don't start whining already!


Downloads

The Result:

FQTKLVOLWXJXVU0.png
1000038754.jpg
20240602_183646.jpg

The total cost of this project will be around $60 - $70 depending on the materials you have. This project is a relief for the plants in your garden. Global warming nowadays is reducing the amount of rainfall and increasing temperature. This will be a cause for droughts in the world which might leave people killing each other for a piece of bread. Countries will invade other countries which would be capable of producing food. The stories we read in the thriller books could turn out to be real in the near future! This project can be used in a large-scale agricultural land too, to increase the yield of subsistence farmers and increase the yield as well. Even a small increase in yield of farmers throughout the world could be sufficient for the growing population. Just Imagine how much impact could a small, affordable idea could do! In fact, this project saves more water than traditional methods. So, equip it in your garden as fast as you can! Your plants will bless you!

I am attaching the working of the project and the prototype that could be implemented in the world.

I am also attaching demonstration in the file below.

the link:

https://drive.google.com/file/d/1cgj2b5TdZutS0flB_upFtKCQjmK84-0E/view?usp=sharing

In the future I would also like to add a machine learning model to the project which takes the weather forecast data via APIs and program the model to optimize the time for irrigation during the peak summer to reduce loss of water through evaporation. The farmers in the countryside would find the product very beneficial.

Thanks

Regards and best wishes for the planet.

Video

Automatic Irrigation System