Drawing from my 18+ years of expertise in the tech industry and now as an advisor, I can confidently say that smart farming and IoT technology are transforming plant care. One key challenge for IoT companies is gathering and utilizing data centrally at a low cost. Building on this premise in this tech post, I’ll demonstrate how to create a simple IoT system using an Arduino to monitor soil moisture levels and store the data via an API. The system will use a sensor to collect soil data, send it to a PHP-based API, and store it in a MySQL database for analysis. This setup allows you to monitor moisture trends and improve your watering routine for optimal plant health.
Prerequisites
Hardware:
- Arduino (Uno/Nano)
- Soil Moisture Sensor
- Wi-Fi Module (ESP8266/ESP32)
- Jumper Wires
- Breadboard
- Power Supply
Software:
- PHP (for the API)
- MySQL (for storing data)
- Arduino IDE (for coding)
- Postman (for API testing)
Step 1: Setting Up Arduino to Measure Soil Moisture
Start by connecting your soil moisture sensor to the Arduino. The sensor will measure the soil’s moisture content and send the readings to the Arduino. You will use a Wi-Fi module (ESP8266/ESP32) to push this data to a cloud server.
Basic Arduino understanding before coding:
- VCC of the sensor connects to 5V on the Arduino.
- GND of the sensor connects to GND on the Arduino.
- AO (Analog Output) connects to A0 on the Arduino for reading analog signals.
- The ESP8266/ESP32 module connects to the Arduino for Wi-Fi communication.
Arduino Code to Collect and Send Moisture Data:
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "your-SSID";
const char* password = "your-password";
const char* apiEndpoint = "http://your-server.com/soil-data"; // PHP API endpoint
int moisturePin = A0; // Pin connected to the moisture sensor
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
int moistureLevel = analogRead(moisturePin);
Serial.print("Moisture Level: ");
Serial.println(moistureLevel);
HTTPClient http;
WiFiClient client;
String postData = "moisture=" + String(moistureLevel);
http.begin(client, apiEndpoint);
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST(postData); // Send POST request
if (httpCode > 0) {
String response = http.getString();
Serial.println("Server response: " + response);
} else {
Serial.println("Error sending data to server");
}
http.end();
delay(60000); // Wait 60 seconds before sending data again
}
Step 2: Creating a PHP API to Store Data
You’ll need a simple PHP API to receive the soil moisture data and store it in a MySQL database. This API acts as the middleman between your Arduino and the cloud storage.
PHP Code to Store Moisture Data:
<?php
$servername = "your-server-name";
$username = "your-username";
$password = "your-password";
$dbname = "IoT_SoilData";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$moisture = $_POST['moisture'];
$sql = "INSERT INTO MoistureLevels (moisture_level, timestamp) VALUES ('$moisture', NOW())";
if ($conn->query($sql) === TRUE) {
echo "Data stored successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
This script accepts moisture data via a POST request and stores it in the MoistureLevels table of your MySQL database.
Step 3: Setting Up MySQL Database
Your MySQL database will store all the moisture data for later retrieval and analysis. Here’s how to create the necessary table:
SQL Schema for MySQL:
CREATE DATABASE IoT_SoilData;
USE IoT_SoilData;
CREATE TABLE MoistureLevels (
id INT AUTO_INCREMENT PRIMARY KEY,
moisture_level INT NOT NULL,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
This schema creates a table called MoistureLevels with columns for the moisture level and timestamp.
Step 4: Retrieving the Last 7 Days of Data
To visualize trends in soil moisture, create a PHP API that retrieves the last seven days of moisture data. This will help you analyze how the soil’s moisture level changes over time.
PHP Code to Get Last 7 Days of Data:
<?php
$servername = "your-server-name";
$username = "your-username";
$password = "your-password";
$dbname = "IoT_SoilData";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT moisture_level, timestamp FROM MoistureLevels WHERE timestamp >= NOW() - INTERVAL 7 DAY ORDER BY timestamp DESC";
$result = $conn->query($sql);
$data = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode([]);
}
$conn->close();
?>
This script retrieves the last 7 days’ worth of moisture readings, ordered by timestamp. The data is returned as a JSON array, which can be used for visualization.
Step 5: Testing Your API with Postman
Before integrating the system, it’s essential to test both APIs using Postman:
- Sending Moisture Data:
Use a POST request tohttp://your-server.com/soil-data
with a form data parameter likemoisture=500
. - Retrieving Moisture Data:
Send a GET request tohttp://your-server.com/get-soil-data
to retrieve the moisture levels from the last seven days.
This tech concept is the first step toward building smart farming solutions for students and aspiring startup creators. I’ve kept the concept focused strictly on programming for data streaming. For more detailed information on Arduino, check out the numerous YouTube tutorials available. Use this framework to create your own fully functional IoT project that monitors soil moisture levels with an Arduino, a PHP API, and MySQL as the cloud database. This project is just the beginning. You can extend it by adding features like automatic watering, visual dashboards, or SMS/Chat/eMail notifications when the soil moisture drops below a threshold.
#AskDushyant
#TechConcept #IoT #SmartFarming #PHP #MySQL #Arduino
Note: The example and pseudo code is for illustration only. You must modify and experiment with the concept to meet your specific needs.
Leave a Reply