Skip to content

Commit

Permalink
Dev (#2)
Browse files Browse the repository at this point in the history
* add: Add Arduino code for AWS IoT integration

* refactor: Refactor Arduino code structure and file organization

* add: Add .gitignore file to exclude AWS data and ArduinoCode/secrets.h

* add: readme Guide for arduino code

* refactor: Update readme

* refactor: Update AWS IoT credentials in ArduinoCode/secrets.h

* refactor: readme
  • Loading branch information
umerghafoor authored Jun 21, 2024
1 parent 654913a commit 0eec569
Show file tree
Hide file tree
Showing 7 changed files with 306 additions and 27 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
AWS data
ArduinoCode/secrets.h
116 changes: 116 additions & 0 deletions ArduinoCode/ArduinoCode.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
#include "DHT.h"
#include "secrets.h"
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "WiFi.h"

#define DHTPIN 14 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11

#define AWS_IOT_PUBLISH_TOPIC "esp32/pub"
#define AWS_IOT_SUBSCRIBE_TOPIC "esp32/sub"

float h ;
float t;

DHT dht(DHTPIN, DHTTYPE);

WiFiClientSecure net = WiFiClientSecure();
PubSubClient client(net);

void connectAWS()
{
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);

Serial.println("Connecting to Wi-Fi");

while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}

// Configure WiFiClientSecure to use the AWS IoT device credentials
net.setCACert(AWS_CERT_CA);
net.setCertificate(AWS_CERT_CRT);
net.setPrivateKey(AWS_CERT_PRIVATE);

// Connect to the MQTT broker on the AWS endpoint we defined earlier
client.setServer(AWS_IOT_ENDPOINT, 8883);

// Create a message handler
client.setCallback(messageHandler);

Serial.println("Connecting to AWS IOT");

while (!client.connect(THINGNAME))
{
Serial.print(".");
delay(100);
}

if (!client.connected())
{
Serial.println("AWS IoT Timeout!");
return;
}

// Subscribe to a topic
client.subscribe(AWS_IOT_SUBSCRIBE_TOPIC);

Serial.println("AWS IoT Connected!");
}

void publishMessage()
{
StaticJsonDocument<200> doc;
doc["humidity"] = h;
doc["temperature"] = t;
char jsonBuffer[512];
serializeJson(doc, jsonBuffer); // print to client

client.publish(AWS_IOT_PUBLISH_TOPIC, jsonBuffer);
}

void messageHandler(char* topic, byte* payload, unsigned int length)
{
Serial.print("incoming: ");
Serial.println(topic);

StaticJsonDocument<200> doc;
deserializeJson(doc, payload);
const char* message = doc["message"];
Serial.println(message);
}

void setup()
{
Serial.begin(115200);
connectAWS();
dht.begin();
}

void loop()
{
h = dht.readHumidity();
t = dht.readTemperature();


if (isnan(h) || isnan(t) ) // Check if any reads failed and exit early (to try again).
{
Serial.println(F("Failed to read from DHT sensor!"));
return;
}

Serial.print(F("Humidity: "));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
Serial.println(F("°C "));

publishMessage();
client.loop();
delay(1000);
}
72 changes: 72 additions & 0 deletions ArduinoCode/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# ESP32 DHT11 Sensor with AWS IoT Core: Documentation and Setup Guide

This code provides a basic structure for connecting an ESP32 development board with a DHT11 sensor to AWS IoT Core for publishing temperature and humidity readings.

## Components Used

* ESP32 Development Board
* DHT11 Sensor
* Breadboard and Jumper Wires
* WiFi Connection (SSID and Password)
* AWS Account (Free Tier Available)

## Software Required

* Arduino IDE ([https://support.arduino.cc/hc/en-us/articles/360019833020-Download-and-install-Arduino-IDE](https://support.arduino.cc/hc/en-us/articles/360019833020-Download-and-install-Arduino-IDE))
* ArduinoJson Library ([https://github.com/bblanchon/ArduinoJson](https://github.com/bblanchon/ArduinoJson))
* WiFiClientSecure Library (included in Arduino IDE)
* PubSubClient Library ([https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.h](https://github.com/knolleary/pubsubclient/blob/master/src/PubSubClient.h))

## AWS IoT Core Setup

1. Create an AWS Account if you don't have one already.
2. Go to the AWS IoT Core service ([https://aws.amazon.com/iot/](https://aws.amazon.com/iot/)).
3. Create a "Thing" which represents your ESP32 device.
4. Download the certificate and private key files associated with the thing.
5. Note down the AWS IoT endpoint address.

## Code Explanation

### Libraries

* `DHT.h`: Provides functions to interact with the DHT sensor.
* `secrets.h` (**Replace with your actual file**): Stores sensitive information like WiFi credentials and AWS certificates (placeholders included in the provided code).
* `WiFiClientSecure.h`: Enables secure communication with AWS IoT Core using certificates.
* `PubSubClient.h`: Manages communication with the MQTT broker on AWS IoT Core.
* `ArduinoJson.h`: Enables working with JSON data format for sending sensor readings.
* `WiFi.h`: Provides WiFi connection functionalities.

### Constants

* `DHTPIN`: Defines the pin connected to the DHT sensor (change if using a different pin).
* `DHTTYPE`: Specifies the DHT sensor type (DHT11 in this case).
* `AWS_IOT_PUBLISH_TOPIC`: Topic used to publish sensor data to AWS IoT Core.
* `AWS_IOT_SUBSCRIBE_TOPIC` (**Optional**): Topic for subscribing to messages from AWS (not used in this example).

### Global Variables

* `h`: Stores humidity reading.
* `t`: Stores temperature reading.
* `dht`: Instance of the DHT library for interacting with the sensor.
* `net`: Instance of WiFiClientSecure for secure communication.
* `client`: Instance of PubSubClient for MQTT communication.

### Functions

* `connectAWS()`: Connects to the WiFi network and then to the AWS IoT Core endpoint using the provided credentials.
* `publishMessage()`: Creates a JSON document with sensor readings and publishes it to the defined topic on AWS IoT Core.
* `messageHandler()`: (**Optional**) Handles incoming messages on the subscribed topic (not used in this example).
* `setup()`: Initializes serial communication, connects to AWS, and starts the DHT sensor.
* `loop()`: Reads sensor data, checks for validity, publishes data to AWS, and loops with a delay.

### Setup Guide

1. Install the required libraries in the Arduino IDE. Library managers can be found under **Tools > Manage Libraries**.
2. In `secrets.h`, define the following constants replacing placeholders with your actual values:
* `#define WIFI_SSID "your_wifi_ssid"`
* `#define WIFI_PASSWORD "your_wifi_password"`
* `#define THINGNAME "your_thing_name"` (replace with the name you created in AWS IoT Core)
* Update the certificate definition strings (`AWS_CERT_CA`, `AWS_CERT_CRT`, and `AWS_CERT_PRIVATE`) by replacing the placeholder content with your downloaded certificates and private key. You can use online tools to convert the downloaded PEM files to a format suitable for the code (check online resources for specific methods).
3. Connect the DHT11 sensor to the ESP32 board according to the pin definition (`DHTPIN`) in the code.
4. Connect the ESP32 board to your computer using a USB cable.
5. In the Arduino IDE, select the appropriate board type for your ESP32
34 changes: 34 additions & 0 deletions ArduinoCode/secrets.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <pgmspace.h>

#define SECRET
#define THINGNAME "ESP32_DHT11" //change this

const char WIFI_SSID[] = ""; //change this
const char WIFI_PASSWORD[] = ""; //change this
const char AWS_IOT_ENDPOINT[] = ""; //change this

// Amazon Root CA 1
static const char AWS_CERT_CA[] PROGMEM = R"EOF(
-----BEGIN CERTIFICATE-----

-----END CERTIFICATE-----
)EOF";
// Device Certificate //change this
static const char AWS_CERT_CRT[] PROGMEM = R"KEY(
-----BEGIN CERTIFICATE-----

-----END CERTIFICATE-----


)KEY";
// Device Private Key //change this
static const char AWS_CERT_PRIVATE[] PROGMEM = R"KEY(
-----BEGIN RSA PRIVATE KEY-----

-----END RSA PRIVATE KEY-----



)KEY";
95 changes: 78 additions & 17 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,92 @@

The IOT Plant Monitoring System is a project that aims to monitor the health and well-being of plants using Internet of Things (IoT) technology.

## Goals
## components

- Real-time monitoring of plant parameters such as temperature, humidity, and soil moisture.
- Data visualization and analysis for better plant management.
- Alerts and notifications for critical plant conditions.
- Remote control and automation of plant care tasks.
This project consists of three main components:

## Installation
1. **ESP32 Code**: Reads soil moisture data and sends it to a server.
2. **PHP Server Script**: Receives and stores soil moisture data in a MySQL database.
3. **Python GUI Application**: Fetches and displays the data from the database with smooth plots.

To install the IOT Plant Monitoring System, follow these steps:
## Components and Their Functions

1. Clone the repository:
### 1. ESP32 Code (`main.ino`)

```bash
git clone https://github.com/your-username/Iot-PLant-Monitoring-System.git
```
This code reads the soil moisture value from a sensor connected to the ESP32 and sends it to a server via an HTTP POST request.

2. Programing Arduino
#### Required Libraries

use sketch_dec04.ino for programming code
- WiFi.h
- HTTPClient.h

## Usage
#### Setup Instructions

To use the IOT Plant Monitoring System, follow these steps:
- Connect the soil moisture sensor to the specified pin (`soilMoisturePin = 32`).
- Update the WiFi credentials (`ssid` and `password`) and the server URL (`URL`).
- Upload the code to the ESP32.

## License
#### Key Functions

The IOT Plant Monitoring System is licensed under the MIT License. See the [LICENSE](./LICENSE) file for more details.
- **connectWiFi()**: Connects the ESP32 to the WiFi network.
- **loop()**: Reads the soil moisture sensor value, calculates the moisture percentage, and sends the data to the server.

### 2. PHP Server Script (`test_data.php`)

This script receives the soil moisture data from the ESP32 and stores it in a MySQL database.
#### Setup Instructions

- Ensure you have a MySQL server running.
- Create a database named `soilmoisture_db` and a table named `dht11` with columns `Moisture`, `DateTime`, and `ID`.
- Update the database credentials (`hostname`, `username`, `password`, `database`) in the script.
- Deploy the script on a web server.

#### Key Functions

- Connects to the MySQL database.
- Inserts the received soil moisture data into the `dht11` table.

### 3. Python GUI Application (`main.py`)

This application fetches the last 25 and 500 entries from the database and displays them as smooth plots using Tkinter and Matplotlib.

#### Required Libraries

- mysql.connector
- tkinter
- ttk
- matplotlib
- scipy
- numpy

#### Setup Instructions

- Ensure you have Python and the required libraries installed.
- Update the MySQL database credentials (`db_config`).
- Run the script to start the GUI.

#### Key Functions

- **fetch_last_entries_and_show_smooth_plots()**: Fetches data from the database and updates the plots.
- **Tkinter GUI**: Displays the original data and plots in a blue-themed window.

---

## Complete Steps to Run the Project

1. **ESP32 Code**:
- Connect the soil moisture sensor to the ESP32.
- Update WiFi credentials and server URL in the code.
- Upload the code to the ESP32.

2. **PHP Server Script**:
- Set up a MySQL database and table.
- Update the database credentials in the script.
- Deploy the script on a web server.

3. **Python GUI Application**:
- Install required libraries using `pip install mysql-connector-python tkinter matplotlib scipy numpy`.
- Update the MySQL database credentials in the script.
- Run the script using `python main.py`.

With these steps, your soil moisture monitoring system should be fully functional, allowing you to read, send, store, and visualize soil moisture data.
12 changes: 3 additions & 9 deletions sketch_dec04a.ino
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
const int soilMoisturePin = 32; // Replace with the actual pin connected to the soil moisture sensor


String URL = "http://192.168.10.14/dht11_project/test_data.php";
String URL = "http://192.168.10.14/dht11_project/test_data.php"; // Replace with the actual URL of the server

const char* ssid = "realme 6i";
const char* password = "hafizah9";
const char* ssid = "Redmi 12C"; // Replace with the actual SSID
const char* password = "password"; // Replace with the actual password

int moisture = 0;

Expand All @@ -32,7 +32,6 @@ void loop() {
Serial.print(moisturePercentage);
Serial.println("%");


if(WiFi.status() != WL_CONNECTED){
connectWiFi();
}
Expand All @@ -55,11 +54,6 @@ void loop() {
delay(5000);
}






void connectWiFi() {
WiFi.mode(WIFI_OFF);
delay(1000);
Expand Down
2 changes: 1 addition & 1 deletion test_data.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

$hostname = "localhost";
$username = "root";
$password = "hafizalihamza9";
$password = "password";
$database = "soilmoisture_db";

$conn = mysqli_connect($hostname, $username, $password, $database);
Expand Down

0 comments on commit 0eec569

Please sign in to comment.