1
2
3#include <ESP8266WiFi.h>
4#include <PubSubClient.h>
5
6#define WIFISSID "Abctest"
7#define PASSWORD "0oOP8QW-R54-OFg@yJ"
8#define TOKEN "BBFF-Zh7ucB7cvbDmIdPHXTRYVHhmNKWOwy"
9#define MQTT_CLIENT_NAME "myecgsensor"
10#define SENSOR A0
11
12
13
14#define VARIABLE_LABEL "myecg"
15#define DEVICE_LABEL "esp8266"
16
17
18
19
20
21
22char mqttBroker[] = "industrial.api.ubidots.com";
23char payload[100];
24char topic[150];
25
26char str_sensor[10];
27
28
31WiFiClient ubidots;
32PubSubClient client(ubidots);
33
34void callback(char* topic, byte* payload, unsigned int length) {
35 char p[length + 1];
36 memcpy(p, payload, length);
37 p[length] = NULL;
38 Serial.write(payload, length);
39 Serial.println(topic);
40}
41
42void reconnect() {
43
44 while (!client.connected()) {
45 Serial.println("Attempting MQTT connection...");
46
47
48 if (client.connect(MQTT_CLIENT_NAME, TOKEN, "")) {
49 Serial.println("Connected");
50 } else {
51 Serial.print("Failed, rc=");
52 Serial.print(client.state());
53 Serial.println(" try again in 2 seconds");
54
55 delay(2000);
56 }
57 }
58}
59
60
63void setup() {
64 Serial.begin(115200);
65 WiFi.begin(WIFISSID, PASSWORD);
66
67 pinMode(SENSOR, INPUT);
68
69 Serial.println();
70 Serial.print("Waiting for WiFi...");
71
72 while (WiFi.status() != WL_CONNECTED) {
73 Serial.print(".");
74 delay(500);
75 }
76
77 Serial.println("");
78 Serial.println("WiFi Connected");
79 Serial.println("IP address: ");
80 Serial.println(WiFi.localIP());
81 client.setServer(mqttBroker, 1883);
82 client.setCallback(callback);
83}
84
85void loop() {
86 if (!client.connected()) {
87 reconnect();
88 }
89
90 sprintf(topic, "%s%s", "/v1.6/devices/", DEVICE_LABEL);
91 sprintf(payload, "%s", "");
92 sprintf(payload, "{\\"%s\\":", VARIABLE_LABEL);
93
94 float myecg = analogRead(SENSOR);
95
96
97 dtostrf(myecg, 4, 2, str_sensor);
98
99 sprintf(payload, "%s {\\"value\\": %s}}", payload, str_sensor);
100 Serial.println("Publishing data to Ubidots Cloud");
101 client.publish(topic, payload);
102 client.loop();
103 delay(10);
104}
105