Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- // Update these with values suitable for your network.
- const char* ssid = "";
- const char* password = "";
- const char* mqtt_server = "mqtt.cheerlights.com";
- #define mqtt_port 1883
- #define MQTT_USER ""
- #define MQTT_PASSWORD ""
- #define MQTT_SERIAL_RECEIVER_CH "cheerlightsRGB"
- WiFiClient wifiClient;
- PubSubClient client(wifiClient);
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- randomSeed(micros());
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Create a random client ID
- String clientId = "ESP32Client-";
- clientId += String(random(0xffff), HEX);
- // Attempt to connect
- if (client.connect(clientId.c_str(),MQTT_USER,MQTT_PASSWORD)) {
- Serial.println("connected");
- //Once connected,...
- // ... and resubscribe
- client.subscribe(MQTT_SERIAL_RECEIVER_CH);
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- // Wait 5 seconds before retrying
- delay(5000);
- }
- }
- }
- void callback(char* topic, byte *payload, unsigned int length) {
- Serial.println("-------new message from broker-----");
- Serial.print("channel:");
- Serial.println(topic);
- Serial.print("data:");
- Serial.write(payload, length);
- Serial.println();
- }
- void setup() {
- pinMode(10, OUTPUT);
- Serial.begin(115200);
- Serial.println("starting....");
- Serial.setTimeout(500);// Set time out for
- setup_wifi();
- client.setServer(mqtt_server, mqtt_port);
- client.setCallback(callback);
- reconnect();
- }
- void loop() {
- client.loop();
- digitalWrite(10, HIGH); // turn the LED on (HIGH is the voltage level)
- delay(1000); // wait for a second
- digitalWrite(10, LOW); // turn the LED off by making the voltage LOW
- delay(1000); // wait for a second
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement