ESP8266 - Control - Via - Internet - Adafr at Main Hockythuatchannel - ESP8266 GitHub
ESP8266 - Control - Via - Internet - Adafr at Main Hockythuatchannel - ESP8266 GitHub
ESP8266 / control_via_internet_adafr
1 #include <ESP8266WiFi.h>
2 #include "Adafruit_MQTT.h"
3 #include "Adafruit_MQTT_Client.h"
4 #define led LED_BUILTIN
5
6 #define WLAN_SSID "FreeWifi" // Your SSID
7 #define WLAN_PASS "freepass" // Your password
8
9 #define AIO_SERVER "io.adafruit.com"
10 #define AIO_SERVERPORT 1883
11 #define AIO_USERNAME ""
12 #define AIO_KEY ""
13
14 //WIFI CLIENT
15 WiFiClient client;
16
17 Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
18
19 Adafruit_MQTT_Subscribe _LED = Adafruit_MQTT_Subscribe(&mqtt, AIO_USERNAME"/feeds/LED");
20
21 void MQTT_connect();
22
23 void setup() {
24 Serial.begin(115200);
25
26 pinMode(led, OUTPUT);
27
28
29 // Connect to WiFi access point.
30 Serial.println(); Serial.println();
31 Serial.print("Connecting to ");
32 Serial.println(WLAN_SSID);
33
34 WiFi.begin(WLAN_SSID, WLAN_PASS);
35 while (WiFi.status() != WL_CONNECTED) {
36 delay(500);
37 Serial.print(".");
38 }
39 Serial.println();
40
41 Serial.println("WiFi connected");
42 Serial.println("IP address: ");
43 Serial.println(WiFi.localIP());
44
45 mqtt.subscribe(&_LED);
46
47 }
48
49 void loop() {
50
51 MQTT_connect();
52
53
54 Adafruit_MQTT_Subscribe *subscription;
55 while ((subscription = mqtt.readSubscription(20000))) {
56 if (subscription == &_LED) {
57 Serial.print(F("Got: "));
58 Serial.println((char *)_LED.lastread);
59 int LED_State = atoi((char *)_LED.lastread);
60 digitalWrite(led, LED_State);
61 }
62 }
63
64
65 }
66
67 void MQTT_connect() {
68 int8_t ret;
69
70 if (mqtt.connected()) {
71 return;
72 }
73
74 Serial.print("Connecting to MQTT... ");
75
76 uint8_t retries = 3;
77
78 while ((ret = mqtt.connect()) != 0) {
79 Serial.println(mqtt.connectErrorString(ret));
80 Serial.println("Retrying MQTT connection in 5 seconds...");
81 mqtt.disconnect();
82 delay(5000);
83 retries--;
84 if (retries == 0) {
85 while (1);
86 }
87 }
88 Serial.println("MQTT Connected!");
89
90 }