#include <WiFi.h>
#include <HTTPClient.h>
// WiFi & ThingSpeak Details
const char* ssid = "vivo V23 5G"; // WiFi SSID
const char* password = ""; // WiFi Password (leave empty if none)
const char* server = "http://api.thingspeak.com/update"; // ThingSpeak API URL
String apiKey = "9WXKR5GNJSCW7S6J"; // Your ThingSpeak API key
// Serial Communication with Arduino (UART2)
#define RX2_PIN 16 // RX2 (Arduino TX to ESP32 RX)
#define TX2_PIN 17 // TX2 (Arduino RX to ESP32 TX)
void setup() {
Serial.begin(115200); // Start serial communication at 115200 baudrate
Serial2.begin(115200, SERIAL_8N1, RX2_PIN, TX2_PIN); // Start serial2 with baudrate 115200
// Connect to WiFi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Check if there's data available from the Arduino
if (Serial2.available()) {
String data = Serial2.readStringUntil('\n'); // Read data till newline
data.trim(); // Remove any leading/trailing spaces
// Parse the data using commas as delimiters
int firstComma = data.indexOf(',');
int secondComma = data.indexOf(',', firstComma + 1);
int thirdComma = data.indexOf(',', secondComma + 1);
if (firstComma > 0 && secondComma > firstComma && thirdComma > secondComma) {
// Extract each sensor value based on commas
String temperature = data.substring(0, firstComma);
String humidity = data.substring(firstComma + 1, secondComma);
String airQuality = data.substring(secondComma + 1, thirdComma);
String soilMoisture = data.substring(thirdComma + 1);
// Print out the data before sending it to ThingSpeak
Serial.println("Sending data to ThingSpeak...");
Serial.println("Temperature: " + temperature);
Serial.println("Humidity: " + humidity);
Serial.println("Air Quality: " + airQuality);
Serial.println("Soil Moisture: " + soilMoisture);
// Send data to ThingSpeak if WiFi is connected
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http; // Create HTTPClient object
String url = String(server) + "?api_key=" + apiKey +
"&field1=" + temperature +
"&field2=" + humidity +
"&field3=" + airQuality +
"&field4=" + soilMoisture;
http.begin(url); // Begin HTTP request
int httpResponseCode = http.GET(); // Make GET request to ThingSpeak
// Check the HTTP response code
if (httpResponseCode > 0) {
Serial.println("Data Sent Successfully!");
} else {
Serial.print("Error: ");
Serial.println(httpResponseCode); // Print the error code if failure
}
http.end(); // End HTTP request
}
}
}
delay(2000); // Delay of 2 seconds before sending the next data
}