Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <WiFi.h>
- #include <PubSubClient.h>
- #include <Adafruit_NeoPixel.h>
- const char* ssid = "raspiNET";
- const char* password = "raspiPASS";
- const char* mqtt_server = "192.168.8.1";
- const char* topicRed = "ledsfantasma/red";
- const char* topicGreen = "ledsfantasma/green";
- const char* topicBlue = "ledsfantasma/blue";
- const char* topicBrightness = "ledsfantasma/bright";
- #define LED_PIN 12
- #define NUM_LEDS 5
- Adafruit_NeoPixel pixels(NUM_LEDS, LED_PIN, NEO_GRB + NEO_KHZ800);
- WiFiClient wifiClient;
- PubSubClient mqttClient(wifiClient);
- int red = 0, green = 0, blue= 0, bright = 255;
- void setup_wifi() {
- delay(10);
- Serial.println();
- Serial.print("Conectando a ");
- Serial.println(ssid);
- WiFi.mode(WIFI_STA);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("\nWiFi conectado!");
- Serial.println("Direccion IP: ");
- Serial.println(WiFi.localIP());
- }
- void reconnect() {
- while (!mqttClient.connected()) {
- Serial.print("Intentando conexion MQTT...");
- String clientId = "ESPClient-";
- clientId += String(random(0xffff), HEX);
- if (mqttClient.connect(clientId.c_str())) {
- Serial.println("Conectado");
- mqttClient.subscribe(topicRed);
- mqttClient.subscribe(topicGreen);
- mqttClient.subscribe(topicBlue);
- mqttClient.subscribe(topicBrightness);
- } else {
- Serial.print("Error, rc=");
- Serial.print(mqttClient.state());
- Serial.println("; probaremos de nuevo en 5 segundos");
- delay(5000);
- }
- }
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Mensaje recibido [");
- Serial.print(topic);
- Serial.print("] ");
- String payloadSTR;
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- payloadSTR.concat(String((char)payload[i]));
- }
- Serial.println();
- int value = payloadSTR.toInt();
- String topicSTR = String(topic);
- Serial.println(topicSTR);
- if (topicSTR.endsWith("red")) red = value;
- else if (topicSTR.endsWith("green")) green = value;
- else if (topicSTR.endsWith("blue")) blue = value;
- else if (topicSTR.endsWith("bright")) bright = value;
- pixels.fill(pixels.Color(red, green, blue), 0);
- pixels.setBrightness(bright);
- pixels.show();
- }
- void setup() {
- Serial.begin(115200);
- setup_wifi();
- mqttClient.setServer(mqtt_server, 1883);
- mqttClient.setCallback(callback);
- pixels.begin();
- pixels.show();
- }
- void loop() {
- if (!mqttClient.connected()) {
- reconnect();
- }
- mqttClient.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement