Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Basic WiFi MQTT example
- This sketch demonstrates the capabilities of the pubsub library in combination
- with the WiFi101 library.
- It connects to an MQTT server then:
- - publishes "hello world" to the topic "outTopic" every two seconds
- - subscribes to the topic "inTopic", printing out any messages
- it receives. NB - it assumes the received payloads are strings not binary
- - If the first character of the topic "inTopic" is an 1, switch ON the ESP Led,
- else switch it off
- It will reconnect to the server if the connection is lost using a blocking
- reconnect function. See the 'mqtt_reconnect_nonblocking' example for how to
- achieve the same result without blocking the main loop.
- */
- #include <WiFi101.h>
- #include <PubSubClient.h>
- #include "arduino_secrets.h"
- #define TOPIC "NWAFabLab/arduino/test"
- #define USERNAME "ahnelson"
- char ssid[] = "FabLab";
- char password[] = "FreakyF@y";
- // Status
- int status = WL_IDLE_STATUS;
- const char* mqtt_server = "broker.mqtt-dashboard.com";
- int led1_status = 0;
- WiFiClient wifiClient;
- PubSubClient client(wifiClient);
- long lastMsg = 0;
- char msg[100];
- int value = 0;
- void setup() {
- Serial.begin(115200);
- setup_wifi();
- client.setServer(mqtt_server, 1883);
- client.setCallback(callback);
- }
- void setup_wifi() {
- delay(10);
- // We start by connecting to a WiFi network
- Serial.println();
- Serial.print("Connecting to ");
- Serial.println(ssid);
- while (status != WL_CONNECTED) {
- status = WiFi.begin(ssid, password);
- }
- Serial.println("");
- Serial.println("WiFi connected");
- Serial.println("IP address: ");
- Serial.println(WiFi.localIP());
- }
- void callback(char* topic, byte* payload, unsigned int length) {
- Serial.print("Message arrived [");
- Serial.print(topic);
- Serial.print("] ");
- int i = 0;
- char angles[length];
- for(i = 0;i<length;i++){
- angles[i] = (char)payload[i];
- }
- Serial.println(angles);
- char* token;
- token = strtok(angles,",");
- while(token != NULL){
- Serial.print(token);
- token = strtok(NULL,",");
- }
- Serial.println("");
- }
- void reconnect() {
- // Loop until we're reconnected
- while (!client.connected()) {
- Serial.print("Attempting MQTT connection...");
- // Attempt to connect
- if (client.connect(USERNAME)) {
- Serial.println("connected");
- // Once connected, subscribe to input channel
- client.subscribe(TOPIC);
- } 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();
- delay(10);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement