vencinachev

LedControl MQTT - ESP32 - TKS

Jan 13th, 2026
112
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.10 KB | None | 0 0
  1. #include <WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. const char* ssid = "Wokwi-GUEST";
  5. const char* password = "";
  6.  
  7. const char* mqtt_server = "test.mosquitto.org";
  8. const char* mqtt_topic  = "tks/led/control";
  9.  
  10. const int LED_PIN = 32;
  11.  
  12. WiFiClient espClient;
  13. PubSubClient client(espClient);
  14.  
  15. void callback(char* topic, byte* payload, unsigned int length) {
  16.   String msg;
  17.   for (unsigned int i = 0; i < length; i++) {
  18.     msg += (char)payload[i];
  19.   }
  20.   msg.trim();
  21.  
  22.   if (msg == "on") {
  23.     digitalWrite(LED_PIN, HIGH);
  24.   }
  25.   else if (msg == "off") {
  26.     digitalWrite(LED_PIN, LOW);
  27.   }
  28. }
  29.  
  30. void setup() {
  31.   pinMode(LED_PIN, OUTPUT);
  32.   digitalWrite(LED_PIN, LOW);
  33.  
  34.   WiFi.begin(ssid, password);
  35.   while (WiFi.status() != WL_CONNECTED) {
  36.     delay(200);
  37.   }
  38.  
  39.   client.setServer(mqtt_server, 1883);
  40.   client.setCallback(callback);
  41.  
  42.   //УНИКАЛНО MQTT CLIENT ID
  43.   String clientId = "wokwi-led-" + WiFi.macAddress();
  44.  
  45.   while (!client.connected()) {
  46.     client.connect(clientId.c_str());
  47.     delay(500);
  48.   }
  49.  
  50.   client.subscribe(mqtt_topic);
  51. }
  52.  
  53. void loop() {
  54.   client.loop();
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment