Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <ESP8266WiFi.h>
- #include <PubSubClient.h>
- // Change the credentials below, so your ESP8266 connects to your router
- const char* ssid = "FRITZ!Box Fon WLAN 7360";
- const char* password = "31034716886687668756";
- // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
- const char* mqtt_server = "barra-home.local";
- const char* mqtt_user = "";
- const char* mqtt_password = "";
- const int LedStrip = 2;
- WiFiClient espClient;
- PubSubClient client(espClient);
- void setup() {
- // put your setup code here, to run once:
- pinMode(LedStrip, OUTPUT);
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- }
- void setup_wifi() {
- delay(10);
- Serial.println();
- Serial.print("Connecting to");
- Serial.println(ssid);
- WiFi.begin(ssid, password);
- while (WiFi.status() != WL_CONNECTED) {
- delay(500);
- Serial.print(".");
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP adress: ");
- Serial.println(WiFi.localIP());
- }
- void reconnect() {
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- if (client.connect("ESP8266Client")) {
- Serial.println("connected");
- client.publish("outTopic", "hello world");
- client.subscribe("home/office/esp1/led/status");
- } else {
- Serial.print("failed, rc=");
- Serial.print(client.state());
- Serial.println(" try again in 5 seconds");
- delay(5000);
- }
- }
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- for (int i = 0; i < length; i++) {
- Serial.print((char)payload[i]);
- }
- Serial.println();
- // Switch on the LED if an 1 was received as first character
- if ((char)payload[0] == '1') {
- digitalWrite(LedStrip, LOW); // Turn the LED on (Note that LOW is the voltage level
- // but actually the LED is on; this is because
- // it is acive low on the ESP-01)
- } else if ((char)payload[0] == '0') {
- digitalWrite(LedStrip, HIGH); // Turn the LED off by making the voltage HIGH
- }
- }
- void loop() {
- // put your main code here, to run repeatedly:
- if (!client.connected()) {
- reconnect();
- }
- client.loop();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement