#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <DHT.h>
#include <OneWire.h>
#include <DallasTemperature.h>
// ================= НАЛАШТУВАННЯ WI-FI ТА TELEGRAM =================
const char* ssid = "Wikwi-GUEST";
const char* password = "";
#define BOTtoken "8627221690:AAFVvrX-pJCsETbqWEo-lzjX0nby8r2BKKQ"
#define CHAT_ID "1009377767"
// ================= НАЛАШТУВАННЯ ПІНІВ =================
#define POT_GAS_PIN 2
#define DHT_PIN 10
#define DHT_TYPE DHT11
#define DS18B20_PIN 7
#define BUTTON_PIN 4
#define LIGHT_PIN 3
#define BUZZER_PIN 5
#define LED_GREEN_PIN 1
#define LED_RED_PIN 0
#define OLED_SDA 8
#define OLED_SCL 9
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 64
const int GAS_THRESHOLD = 1500;
// ================= ОБ'ЄКТИ =================
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
DHT dht(DHT_PIN, DHT_TYPE);
OneWire oneWire(DS18B20_PIN);
DallasTemperature ds18b20(&oneWire);
WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
// Змінні для логіки
bool displayEnabled = true;
bool lastButtonState = HIGH;
unsigned long lastDebounceTime = 0;
unsigned long lastSensorReadTime = 0;
unsigned long lastBotCheckTime = 0;
const unsigned long botCheckInterval = 1000;
float airTemp, humidity, waterTemp;
int gasLevel, lightVal;
// Функція формування клавіатури ТГ
String getButtons() {
String keyboard = "[[\"Отримати дані\"],";
keyboard += "[\"Темп. повітря\", \"Вологість\"],";
keyboard += "[\"Темп. води\", \"Газ\", \"Світло\"]]";
return keyboard;
}
void handleNewMessages(int numNewMessages) {
for (int i = 0; i < numNewMessages; i++) {
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID) continue; // Ігноруємо чужих
String text = bot.messages[i].text;
if (text == "/start" || text == "start") {
String welcome = "Вітаю! Керування пристроєм активовано.\nОберіть дію:";
bot.sendMessageWithReplyKeyboard(chat_id, welcome, "", getButtons(), true);
}
else if (text == "Отримати дані") {
String msg = "📊 Всі дані з пристрою:\n";
msg += "🌡 Повітря: " + String(airTemp, 1) + "°C\n";
msg += "💧 Вологість: " + String(humidity, 0) + "%\n";
msg += "🌊 Вода: " + String(waterTemp, 1) + "°C\n";
msg += "💨 Газ: " + String(gasLevel) + "\n";
msg += "💡 Світло: " + String(lightVal);
bot.sendMessage(chat_id, msg, "");
}
else if (text == "Темп. повітря") bot.sendMessage(chat_id, "🌡 Температура повітря: " + String(airTemp, 1) + "°C", "");
else if (text == "Вологість") bot.sendMessage(chat_id, "💧 Вологість: " + String(humidity, 0) + "%", "");
else if (text == "Темп. води") bot.sendMessage(chat_id, "🌊 Температура води: " + String(waterTemp, 1) + "°C", "");
else if (text == "Газ") bot.sendMessage(chat_id, "💨 Рівень газу: " + String(gasLevel), "");
else if (text == "Світло") bot.sendMessage(chat_id, "💡 Освітленість: " + String(lightVal), "");
}
}
void setup() {
Serial.begin(115200);
analogReadResolution(12);
pinMode(POT_GAS_PIN, INPUT);
pinMode(LIGHT_PIN, INPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
pinMode(BUZZER_PIN, OUTPUT);
pinMode(LED_GREEN_PIN, OUTPUT);
pinMode(LED_RED_PIN, OUTPUT);
digitalWrite(LED_GREEN_PIN, HIGH);
Wire.begin(OLED_SDA, OLED_SCL);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.setTextColor(WHITE);
display.setTextSize(1);
display.setCursor(0, 10);
display.println("Connecting WiFi...");
display.println(ssid);
display.display();
client.setInsecure();
// Підключення до WiFi
Serial.println("\nПідключення до WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi підключено успішно!");
display.clearDisplay();
display.setCursor(0, 10);
display.println("WiFi Connected!");
display.display();
// ================= ОЧИЩЕННЯ СТАРИХ ПОВІДОМЛЕНЬ =================
// Забираємо з пам'яті Телеграму все, що ви натискали, поки плата була вимкнена
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while (numNewMessages) {
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
// ===============================================================
// Відправляємо повідомлення в ТГ після успішного підключення
bot.sendMessage(CHAT_ID, "✅ Пристрій увімкнений та готовий до роботи", "");
dht.begin();
ds18b20.begin();
}
void loop() {
// 1. КНОПКА ЕКРАНУ
int currentButtonState = digitalRead(BUTTON_PIN);
if (currentButtonState == LOW && lastButtonState == HIGH && (millis() - lastDebounceTime > 200)) {
displayEnabled = !displayEnabled;
lastDebounceTime = millis();
if (!displayEnabled) { display.clearDisplay(); display.display(); }
}
lastButtonState = currentButtonState;
// 2. ОПИТУВАННЯ ДАТЧИКІВ
if (millis() - lastSensorReadTime >= 2000) {
lastSensorReadTime = millis();
humidity = dht.readHumidity();
airTemp = dht.readTemperature();
ds18b20.requestTemperatures();
waterTemp = ds18b20.getTempCByIndex(0);
gasLevel = analogRead(POT_GAS_PIN);
lightVal = analogRead(LIGHT_PIN);
// Логіка тривоги
if (gasLevel > GAS_THRESHOLD) {
digitalWrite(LED_RED_PIN, HIGH); digitalWrite(LED_GREEN_PIN, LOW); digitalWrite(BUZZER_PIN, HIGH);
} else {
digitalWrite(LED_RED_PIN, LOW); digitalWrite(LED_GREEN_PIN, HIGH); digitalWrite(BUZZER_PIN, LOW);
}
// Оновлення OLED
if (displayEnabled) {
display.clearDisplay();
display.setCursor(0, 0);
display.print("WiFi: "); display.println(WiFi.status() == WL_CONNECTED ? "OK" : "OFF");
display.println("---------------------");
display.print("Air: "); display.print(airTemp, 1); display.print("C / "); display.print(humidity, 0); display.println("%");
display.print("Water: "); display.print(waterTemp, 1); display.println(" C");
display.print("Gas: "); display.println(gasLevel);
display.print("Light: "); display.println(lightVal);
display.setCursor(0, 56);
display.print(gasLevel > GAS_THRESHOLD ? "!!! DANGER: GAS !!!" : "STATUS: NORMAL");
display.display();
}
}
// 3. ПЕРЕВІРКА ТЕЛЕГРАМ (Більш стабільний варіант)
if (millis() - lastBotCheckTime > botCheckInterval) {
if (WiFi.status() == WL_CONNECTED) {
int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
if (numNewMessages > 0) { // Якщо є нове повідомлення
handleNewMessages(numNewMessages); // Обробляємо його
}
}
lastBotCheckTime = millis();
}
}Loading
esp32-c3-devkitm-1
esp32-c3-devkitm-1