/**
ESP32 + Moisture Sensor + Motor Switch Example for Wokwi
*/
#include <WiFi.h>
#include "ThingSpeak.h"
// Pin Definitions
const int MOISTURE_SENSOR_PIN = 34; // Analog input for moisture sensor
const int MOTOR_SWITCH_PIN = 5; // GPIO pin for motor switch
// WiFi Credentials
const char* WIFI_NAME = "Wokwi-GUEST"; // Replace with your WiFi SSID
const char* WIFI_PASSWORD = ""; // Replace with your WiFi password
// ThingSpeak Configuration
const int myChannelNumber = 2833645; // Replace with your ThingSpeak Channel ID
const char* myApiKey = "EJKBWBE6KY88FUWB"; // Replace with your Write API Key
const char* server = "api.thingspeak.com";
// WiFi Client
WiFiClient client;
void setup() {
// Initialize Serial Monitor
Serial.begin(9600);
// Set up pins
pinMode(MOTOR_SWITCH_PIN, INPUT_PULLUP); // Motor switch as input
// Connect to WiFi
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("WiFi not connected");
}
Serial.println("WiFi connected!");
Serial.println("Local IP: " + String(WiFi.localIP()));
// Set WiFi mode to station
WiFi.mode(WIFI_STA);
// Initialize ThingSpeak
ThingSpeak.begin(client);
}
void loop() {
// Read Moisture Sensor
int sensorValue = analogRead(MOISTURE_SENSOR_PIN);
// Convert sensor value to percentage (adjust min/max values based on your sensor)
float moisturePercentage = map(sensorValue, 1500, 3500, 100, 0); // Example range
moisturePercentage = constrain(moisturePercentage, 0, 100); // Ensure it's between 0-100
// Read Motor Switch State
int motorState = digitalRead(MOTOR_SWITCH_PIN);
// Print data to Serial Monitor
Serial.println("Moisture: " + String(moisturePercentage, 1) + "%");
Serial.println("Motor: " + String(motorState));
// Send data to ThingSpeak
ThingSpeak.setField(1, moisturePercentage); // Field1 for moisture percentage
ThingSpeak.setField(2, motorState); // Field2 for motor status
int x = ThingSpeak.writeFields(myChannelNumber, myApiKey);
if (x == 200) {
Serial.println("Data pushed successfully");
} else {
Serial.println("Push error: " + String(x));
}
Serial.println("---");
// Wait before next update
delay(5000); // Update every 10 seconds
}