Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- const char* ssid = "Wokwi-GUEST";
- const char* password = "";
- const char* mqtt_server = "test.mosquitto.org";
- const char* mqtt_topic = "tks/led/control";
- const int LED_PIN = 32;
- WiFiClient espClient;
- PubSubClient client(espClient);
- void callback(char* topic, byte* payload, unsigned int length) {
- String msg;
- for (unsigned int i = 0; i < length; i++) {
- msg += (char)payload[i];
- }
- msg.trim();
- if (msg == "on") {
- digitalWrite(LED_PIN, HIGH);
- }
- else if (msg == "off") {
- digitalWrite(LED_PIN, LOW);
- }
- }
- void setup() {
- pinMode(LED_PIN, OUTPUT);
- digitalWrite(LED_PIN, LOW);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(200);
- }
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- //УНИКАЛНО MQTT CLIENT ID
- String clientId = "wokwi-led-" + WiFi.macAddress();
- while (!client.connected()) {
- client.connect(clientId.c_str());
- delay(500);
- }
- client.subscribe(mqtt_topic);
- }
- void loop() {
- client.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment