Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #include <ESP8266WiFi.h>
  2. #include <PubSubClient.h>
  3.  
  4. // Change the credentials below, so your ESP8266 connects to your router
  5. const char* ssid = "LTE-wifi";
  6. const char* password = "*ltesch*";
  7.  
  8. // Change the variable to your Raspberry Pi IP address, so it connects to your MQTT broker
  9. const char* mqtt_server = "barra-home.local";
  10. const char* mqtt_user = "";
  11. const char* mqtt_password = "";
  12.  
  13. const int LedStrip = 2;
  14.  
  15. WiFiClient espClient;
  16. PubSubClient client(espClient);
  17.  
  18. void setup() {
  19. // put your setup code here, to run once:
  20. pinMode(LedStrip, OUTPUT);
  21. Serial.begin(115200);
  22. setup_wifi();
  23. client.setServer(mqtt_server, 1883);
  24. client.setCallback(callback);
  25. }
  26.  
  27. void setup_wifi() {
  28. delay(10);
  29. Serial.println();
  30. Serial.print("Connecting to");
  31. Serial.println(ssid);
  32.  
  33. WiFi.begin(ssid, password);
  34. while (WiFi.status() != WL_CONNECTED) {
  35. delay(500);
  36. Serial.print(".");
  37. }
  38. Serial.println("");
  39. Serial.println("WiFi connected");
  40. Serial.println("IP adress: ");
  41. Serial.println(WiFi.localIP());
  42. }
  43.  
  44. void reconnect() {
  45. while (!client.connected()) {
  46. Serial.print("Attempting MQTT connection...");
  47. if (client.connect("ESP8266Client1")) {
  48. Serial.println("connected");
  49. client.subscribe("home/office/esp1/led/status");
  50.  
  51. } else {
  52. Serial.print("failed, rc=");
  53. Serial.print(client.state());
  54. Serial.println(" try again in 5 seconds");
  55. delay(5000);
  56. }
  57. }
  58. }
  59. void callback(char* topic, byte* payload, unsigned int length) {
  60. Serial.print("Message arrived [");
  61. Serial.print(topic);
  62. Serial.print("] ");
  63. for (int i = 0; i < length; i++) {
  64. Serial.print((char)payload[i]);
  65. }
  66. Serial.println();
  67. // Switch on the LED if an 1 was received as first character
  68. if ((char)payload[0] == '1') {
  69. digitalWrite(LedStrip, LOW); // Turn the LED on (Note that LOW is the voltage level
  70. // but actually the LED is on; this is because
  71. // it is acive low on the ESP-01)
  72. } else if ((char)payload[0] == '0') {
  73. digitalWrite(LedStrip, HIGH); // Turn the LED off by making the voltage HIGH
  74. }
  75. }
  76.  
  77. void loop() {
  78. // put your main code here, to run repeatedly:
  79. if (!client.connected()) {
  80. reconnect();
  81. }
  82. client.loop();
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement