Created
October 5, 2016 22:15
-
-
Save AgustinPelaez/74d75ad5ab3eb6008767d8275a815286 to your computer and use it in GitHub Desktop.
A simple MQTT sketch to upload values to Ubidots
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 <LWiFi.h> | |
#include <LWiFiClient.h> | |
#include <PubSubClient.h> | |
// These are the variables you will want to change based on your IOT data streaming account / provider | |
#define TOPIC "/v1.6/devices/YOUR-DEVICE-LABEL" | |
#define TOKEN "YOUR-UBIDOTS-TOKEN | |
#define WIFI_AP "UBIWIFI" | |
#define WIFI_PASSWORD "clave123456789ubi" | |
#define WIFI_AUTH LWIFI_WPA | |
char payload[180]; // Reserve a char to store the Ubidots data. Account for 60 bytes per variable. | |
char le[4]; | |
char mqttBroker[] = "things.ubidots.com"; | |
String response; | |
LWiFiClient c; | |
PubSubClient client(c); | |
int horometro = 0; | |
void reconnect() { | |
// Loop until we're reconnected | |
while (!client.connected()) { | |
Serial.print("Attempting MQTT connection..."); | |
// Attempt to connect | |
if (client.connect("linkit-one",TOKEN,"")) { | |
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 setup() | |
{ | |
Serial.begin(115200); // setup Serial port | |
LWiFi.begin(); | |
// keep retrying until connected to AP | |
Serial.println("Connecting to AP"); | |
while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD))) | |
{ | |
delay(1000); | |
} | |
Serial.println("Wifi connected!"); | |
client.setServer(mqttBroker, 1883); | |
} | |
void loop(){ | |
int temp = analogRead(A0); | |
int presion = analogRead(A1); | |
horometro = horometro + 1; | |
sprintf(payload,"%s", "{\"temperature\":"); | |
sprintf(payload,"%s%d", payload, temp); | |
sprintf(payload,"%s%s", payload, ",\"presion\":"); | |
sprintf(payload,"%s%d", payload, presion); | |
sprintf(payload,"%s%s", payload, ",\"horometro\":"); | |
sprintf(payload,"%s%d", payload, horometro); | |
sprintf(payload,"%s%s", payload, "}"); | |
Serial.println(payload); | |
if (!client.connected()) { | |
reconnect(); | |
} | |
client.publish(TOPIC, payload); | |
client.loop(); | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment