Last active
February 16, 2018 22:02
-
-
Save jaycollett/b1dd513d4a8baaf3719e4c14d889b1d9 to your computer and use it in GitHub Desktop.
Arduino WiFi101 MQTT Example (using PubSubClient by Nick O'Leary)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <SPI.h> | |
#include <WiFi101.h> | |
#include <PubSubClient.h> | |
char ssid[] = "XXXXX"; // your network SSID (name) | |
char pass[] = "XXXXXXXXX"; // your network password (use for WPA, or use as key for WEP) | |
int status = WL_IDLE_STATUS; | |
WiFiClient wificlient; | |
PubSubClient mqttclient(wificlient); | |
void setup() { | |
WiFi.setPins(8,7,4,2); | |
// attempt to connect to WiFi network: | |
while (status != WL_CONNECTED) { | |
Serial.print("Attempting to connect to SSID: "); | |
Serial.println(ssid); | |
// Connect to WPA/WPA2 network. Change this line if using open or WEP network: | |
status = WiFi.begin(ssid, pass); | |
// wait 10 seconds for connection: | |
delay(10000); | |
} | |
Serial.println("Connected to wifi"); | |
if (mqttclient.connect("arduinoClient", "testuser", "testpass")) { | |
mqttclient.publish("Coop/Outside/Temperature","88"); | |
} | |
} | |
void loop() { | |
// put your main code here, to run repeatedly: | |
if (!mqttclient.connected()) { | |
reconnect(); | |
} | |
} | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!mqttclient.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (mqttclient.connect("arduinoClient", "testuser", "testpass")) { | |
Serial.println("connected"); | |
} else { | |
Serial.print("failed, rc="); | |
Serial.print(mqttclient.state()); | |
Serial.println(" try again in 5 seconds"); | |
// Wait 5 seconds before retrying | |
delay(5000); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment