Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- #include <DHT.h>
- // WiFi
- const char* ssid = "Wokwi-GUEST";
- const char* password = "";
- // MQTT
- const char* mqtt_server = "test.mosquitto.org";
- const int mqtt_port = 1883;
- const char* topic_control = "tks/lamp/control";
- const char* topic_temp = "tks/dht22/temperature";
- const char* topic_hum = "tks/dht22/humidity";
- // Хардуер пинове
- const int RELAY_PIN = 32;
- const int DHT_PIN = 33;
- #define DHTTYPE DHT22
- WiFiClient espClient;
- PubSubClient client(espClient);
- DHT dht(DHT_PIN, DHTTYPE);
- // Таймер за изпращане на всеки 2 секунди
- unsigned long lastSendMs = 0;
- const unsigned long SEND_INTERVAL_MS = 2000;
- const bool RELAY_ACTIVE_LOW = false;
- void setRelay(bool on) {
- if (RELAY_ACTIVE_LOW) {
- digitalWrite(RELAY_PIN, on ? LOW : HIGH);
- } else {
- digitalWrite(RELAY_PIN, on ? HIGH : LOW);
- }
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- String msg;
- msg.reserve(length);
- for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
- msg.trim();
- if (String(topic) == topic_control) {
- if (msg == "on") setRelay(true);
- if (msg == "off") setRelay(false);
- }
- }
- void connectWiFi() {
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(200);
- }
- }
- void reconnectMQTT() {
- while (!client.connected()) {
- // уникален clientId !!!
- String clientId = "esp32-dht22-relay-";
- clientId += String((uint32_t)ESP.getEfuseMac(), HEX);
- if (client.connect(clientId.c_str())) {
- client.subscribe(topic_control);
- } else {
- delay(1000);
- }
- }
- }
- void setup() {
- pinMode(RELAY_PIN, OUTPUT);
- setRelay(false);
- dht.begin();
- connectWiFi();
- client.setServer(mqtt_server, mqtt_port);
- client.setCallback(callback);
- reconnectMQTT();
- }
- void loop() {
- if (WiFi.status() != WL_CONNECTED) {
- connectWiFi();
- }
- if (!client.connected()) {
- reconnectMQTT();
- }
- client.loop();
- unsigned long now = millis();
- if (now - lastSendMs >= SEND_INTERVAL_MS) {
- lastSendMs = now;
- float t = dht.readTemperature(); // Celsius
- float h = dht.readHumidity();
- if (!isnan(t)) {
- char buf[16];
- dtostrf(t, 0, 2, buf); // 2 знака след десетичната
- client.publish(topic_temp, buf);
- }
- if (!isnan(h)) {
- char buf[16];
- dtostrf(h, 0, 2, buf);
- client.publish(topic_hum, buf);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment