Consider a specific example, which will make it possible to monitor air temperature and humidity, keep track of variations in metering values per hour and plot a graph of Wi-Fi signal strength with the data refreshing rate of 20 seconds.
Required materials:
Device adding and setting:
Firmware ESP8266:
#include <ESP8266WiFi.h>
#include <Wire.h>
#include "Adafruit_SHT31.h"
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
HTTPClient http;
Adafruit_SHT31 sht31 = Adafruit_SHT31();
//ssid and access password for connection to WI-FI
const char* ssid = "........";
const char* password = "........";
//server address and port
const char* http_server = "VizIoT.com";
const int http_port = 48656;
//VizIoT access key and password Devices (can be found in device settings)
String VizIoT_Device_key = "................";
String VizIoT_Device_pass = "....................";
void setup() {
//Turn on information output in Serial Monitor
Serial.begin(115200);
//Connect to WI-FI
setup_wifi();
Serial.println("Seeking for SHT31-D sensor");
if (! sht31.begin(0x44)) { // put 0x45 for the alternative i2c sensor address
Serial.println("SHT31-D cannot be found");
}
}
void loop() {
String url = String("/update?key=") + VizIoT_Device_key + "&" + "pass=" + VizIoT_Device_pass ;
//read sensor values
float t = sht31.readTemperature();
float h = sht31.readHumidity();
//check information on temperature
if (! isnan(t)) {
Serial.print("Temperature *C = ");
Serial.println(t);
url += String("&tem=") + t;
} else {
Serial.println("Temperature reading error");
}
//check information on air humidity
if (! isnan(h)) {
Serial.print("Hum. % = ");
Serial.println(h);
url += String("&hum=") + h;
} else {
Serial.println("Humidity reading error");
}
if (sendGetRequest(url) == true) {
Serial.println("Data has been sent to the server");
} else {
Serial.println("Error while sending data");
}
//wait 20 seconds
delay(20000);
}
//Wi-Fi connection function
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
//To be connected to WI-FI
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
//Function sending data to the server
int sendGetRequest(String url) {
if (WiFi.status() == WL_CONNECTED) {
http.begin(http_server, http_port, url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
http.end();
if (payload.equals("OK")) {
return true;
} else {
return false;
}
} else {
Serial.println("[HTTP] GET... failed, error!!!\r\n");
Serial.print("httpCode = ");
Serial.println(httpCode);
http.end();
return false;
}
} else {
return false;
}
}
Adding widgets:
Now the setup is complete and you have to wait until your device connected to the server.