Advertisement
Guest User

Untitled

a guest
Mar 25th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.31 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 = "FRITZ!Box Fon WLAN 7360";
  6. const char* password = "31034716886687668756";
  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("ESP8266Client")) {
  48. Serial.println("connected");
  49. client.publish("outTopic", "hello world");
  50. client.subscribe("home/office/esp1/led/status");
  51.  
  52. } else {
  53. Serial.print("failed, rc=");
  54. Serial.print(client.state());
  55. Serial.println(" try again in 5 seconds");
  56. delay(5000);
  57. }
  58. }
  59. }
  60. void callback(char* topic, byte* payload, unsigned int length) {
  61. Serial.print("Message arrived [");
  62. Serial.print(topic);
  63. Serial.print("] ");
  64. for (int i = 0; i < length; i++) {
  65. Serial.print((char)payload[i]);
  66. }
  67. Serial.println();
  68. // Switch on the LED if an 1 was received as first character
  69. if ((char)payload[0] == '1') {
  70. digitalWrite(LedStrip, LOW); // Turn the LED on (Note that LOW is the voltage level
  71. // but actually the LED is on; this is because
  72. // it is acive low on the ESP-01)
  73. } else if ((char)payload[0] == '0') {
  74. digitalWrite(LedStrip, HIGH); // Turn the LED off by making the voltage HIGH
  75. }
  76. }
  77.  
  78. void loop() {
  79. // put your main code here, to run repeatedly:
  80. if (!client.connected()) {
  81. reconnect();
  82. }
  83. client.loop();
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement