#include <WiFi.h>
#include <HTTPClient.h>

// Pin definitions
const int relayPin = 17;
const int buzzerPin = 18;
const int soilPin = 34;  // GPIO pin for analog input (use ADC1 for GPIOs 32-39)

// Threshold and API Key
const int soilThreshold = 40;
const char* apiKey = "K2I6J1JZZMUC26KJ";

// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST";
const char* password = "";

// Function to connect to Wi-Fi
void connectWiFi() {
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi!");
}

// Function to send data to ThingSpeak
void updateThingSpeak(int soilValue, int relayState) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = "https://api.thingspeak.com/update?api_key=" + String(apiKey) + "&field1=" + String(soilValue) + "&field2=" + String(relayState);

    http.begin(url);
    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
      String payload = http.getString();
      Serial.println("Data sent to ThingSpeak: " + payload);
    } else {
      Serial.println("Error sending data to ThingSpeak");
    }
    http.end();
  } else {
    Serial.println("WiFi disconnected. Cannot send data.");
  }
}

void setup() {
  // Initialize Serial Monitor
  Serial.begin(115200);

  // Initialize pins
  pinMode(relayPin, OUTPUT);
  pinMode(buzzerPin, OUTPUT);
  digitalWrite(relayPin, LOW);  // Initially turn off the relay
  digitalWrite(buzzerPin, LOW); // Initially turn off the buzzer

  // Connect to Wi-Fi
  connectWiFi();
}

void loop() {
  // Read soil moisture value (analog input)
  int soilRaw = analogRead(soilPin); 
  Serial.print("soilRaw: ");
  Serial.println(soilRaw);
  // int soilValue = map(soilRaw, 0, 4095, 0, 100); // Map to 0-100 range using built-in map()
  int soilValue = map(1023 - soilRaw, 0, 1023, 0, 100); // Invert the raw value and map to 0-100

  Serial.print("Soil Moisture: ");
  Serial.println(soilValue);

  // Control relay and buzzer based on threshold
  int relayState;
  if (soilValue >= soilThreshold) {
    digitalWrite(relayPin, LOW);  // Turn off relay
    digitalWrite(buzzerPin, LOW); // Turn off buzzer
    relayState = 0;
  } else {
    digitalWrite(relayPin, HIGH); // Turn on relay
    digitalWrite(buzzerPin, HIGH); // Turn on buzzer
    relayState = 1;
  }

  // Update ThingSpeak with soil moisture and relay state
  // updateThingSpeak(soilValue, relayState);

  // Delay before the next reading
  delay(15000); // 15 seconds
}
NOCOMNCVCCGNDINLED1PWRRelay Module