#include <WiFi.h> // Бібліотека для підключення ESP32 до WiFi
#include <WebServer.h> // Бібліотека для створення HTTP веб-сервера
#include <HTTPClient.h> // Для відправки HTTP-запитів
#include <ArduinoJson.h> // Для роботи з JSON даними
#include <LiquidCrystal_I2C.h> // Для роботи з LCD дисплеєм по I2C
#include <DHTesp.h> // Бібліотека для роботи з DHT датчиками
#define led 2 // Пін для підключення світлодіода
const int DHT_SENSOR_PIN = 26; // Пін для датчика температури та вологості (наприклад DHT22)
#define digital_In 25
#define analog_In 34
const char* SSID = "Wokwi-GUEST";
const char* password = "";
const char* openaiApiKey = "b453666eb3d04c1fa7c608375d88f7fc"; // API ключ GPT
const float GAMMA = 0.7;
const float RL10 = 50;
WebServer server(80); // Створення веб-сервера на порту 80
LiquidCrystal_I2C LCD(0x27, 20, 4); // LCD 20x4
DHTesp dht; // Об'єкт для роботи з DHT датчиком (температура, вологість)
// Пороги для кожного параметру (в залежності від виду рослин)
const float MIN_TEMP = 18.0;
const float MAX_TEMP = 30.0;
const float MIN_HUMIDITY = 40.0;
const float MAX_HUMIDITY = 80.0;
unsigned long lastRequestTime = 0;
const unsigned long REQUEST_INTERVAL = 20000; // 20 секунд
// ------------------ ВИКЛИК GPT ------------------
void request_gpt(String prompt) {
Serial.println("Sending request to GPT...");
DynamicJsonDocument doc(1024);
doc["model"] = "gpt-3.5-turbo";
JsonArray messages = doc.createNestedArray("messages");
JsonObject systemMsg = messages.createNestedObject();
systemMsg["role"] = "system";
systemMsg["content"] = "You are a smart plant care assistant.";
JsonObject userMsg = messages.createNestedObject();
userMsg["role"] = "user";
userMsg["content"] = prompt;
HTTPClient http;
String apiUrl = "https://artificialintelligence.openai.azure.com/openai/deployments/test/chat/completions?api-version=2023-05-15";
http.begin(apiUrl);
http.addHeader("Content-Type", "application/json");
http.addHeader("api-key", openaiApiKey);
String body;
serializeJson(doc, body);
int httpCode = http.POST(body);
if (httpCode == 200) {
String response = http.getString();
DeserializationError error = deserializeJson(doc, response);
if (!error) {
String reply = doc["choices"][0]["message"]["content"].as<String>();
Serial.println("GPT reply:\n" + reply);
}
} else {
Serial.println("Error sending request to GPT. HTTP code: " + String(httpCode));
}
http.end();
}
// ------------------ ЗЧИТУВАННЯ ДАНИХ ------------------
float getTemperature() {
return dht.getTemperature();
}
float getHumidity() {
return dht.getHumidity();
}
// ------------------ SETUP ------------------
void setup() {
Serial.begin(115200);
pinMode(digital_In, INPUT);
pinMode(analog_In, INPUT);
pinMode(led, OUTPUT);
WiFi.begin(SSID, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nConnected. IP: " + WiFi.localIP().toString());
LCD.init();
LCD.backlight();
dht.setup(DHT_SENSOR_PIN, DHTesp::DHT22);
float temp = getTemperature();
float humidity = getHumidity();
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Humidity: " + String(humidity, 1) + "%");
LCD.setCursor(0, 1);
LCD.print("Temp: " + String(temp, 1) + "C");
String prompt = "The humidity is " + String(humidity) + "%, and the temperature is " + String(temp) + "°C. ";
if (temp < MIN_TEMP || temp > MAX_TEMP || humidity < MIN_HUMIDITY || humidity > MAX_HUMIDITY) {
prompt += "The conditions are not optimal. Please provide advice on how to improve the environment for the plants.";
} else {
prompt += "The conditions are normal.";
}
request_gpt(prompt);
}
// ------------------ LOOP ------------------
void loop() {
if (millis() - lastRequestTime >= REQUEST_INTERVAL) {
lastRequestTime = millis();
float temp = getTemperature();
float humidity = getHumidity();
int analogValue = analogRead(analog_In);
float voltage = analogValue / 4096.0 * 5.0;
float resistance;
if (voltage >= 4.99)
{ resistance = 999999; }
else { resistance = 2000 * voltage / (5.0 - voltage); }
float lux_a = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1.0 / GAMMA));
lux_a = lux_a/10;
// Debug в Serial Monitor
Serial.print("Analog: "); Serial.print(analogValue);
Serial.print(" | Voltage: "); Serial.print(voltage);
Serial.print(" | Resistance: "); Serial.print(resistance);
Serial.print(" | Lux: "); Serial.println(lux_a);
// Вывод на LCD
LCD.clear();
LCD.setCursor(0, 0);
LCD.print("Temp: " + String(temp, 1) + " C");
LCD.setCursor(0, 1);
LCD.print("Humidity: " + String(humidity, 1) + " %");
LCD.setCursor(0, 2); // 3-я строка (индекс 2)
LCD.print("Light: " + String(lux_a, 1) + " lux");
LCD.setCursor(0, 3); // 4-я строка (индекс 3)
if (temp < MIN_TEMP || temp > MAX_TEMP || humidity < MIN_HUMIDITY || humidity > MAX_HUMIDITY) {
LCD.print("Status: Warning!");
} else {
LCD.print("Status: Optimal");
}
// Формируем запрос к GPT
String prompt = "The humidity is " + String(humidity) + "%, and the temperature is " + String(temp) + "°C. ";
if (temp < MIN_TEMP || temp > MAX_TEMP || humidity < MIN_HUMIDITY || humidity > MAX_HUMIDITY) {
prompt += "The conditions are not optimal. Please provide advice on how to improve the environment for the plants.";
} else {
prompt += "The conditions are normal.";
}
request_gpt(prompt);
}
delay(500);
}