Skip to content

Instantly share code, notes, and snippets.

@roboticboyer
Last active November 5, 2017 17:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roboticboyer/b47236a097a61984db24a968e993af42 to your computer and use it in GitHub Desktop.
Save roboticboyer/b47236a097a61984db24a968e993af42 to your computer and use it in GitHub Desktop.
MQTT_test
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Update these with values suitable for your network.
//const char *ssid = "localwifi";
//const char *password = "localpassword";
const char *ssid = "MyAP";
const char *password = "";
//const char* mqtt_server = "192.168.1.104";
//const char* mqtt_server = "192.168.1.250";
const char* mqtt_server = "192.168.4.1";
WiFiClient espClient;
PubSubClient client(espClient);
void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA); //Adding this command the ESP now work with uMQTT AP!!!
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP8266Client")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment