Last active
March 26, 2019 06:06
-
-
Save IdrisCytron/a7afe3d8921c9f750627fd21acfa969a to your computer and use it in GitHub Desktop.
Logging sensor's data into Favoriot IoT platform using ESP32 board.
This file contains 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
/* | |
* Board: Node32 Lite (ESP32 Dev Module) | |
* https://www.cytron.io/p-node32-lite-wifi-and-amp;-bluetooth-development-kit | |
*/ | |
#include <WiFi.h> | |
#include <HTTPClient.h> | |
#include <ArduinoJson.h> | |
#include <SimpleDHT.h> | |
#define APIKEY "Your Favoriot APIKEY" | |
#define DEVICE_DEV_ID "Your Device Developer ID" | |
const int SEN_PIN = 25; | |
SimpleDHT22 dht22(SEN_PIN); | |
const char ssid[] = "Your WiFi SSID"; | |
const char password[] = "Your WiFi Password"; | |
float temperature = 0; | |
float humidity = 0; | |
long previousMillis = 0; | |
int interval = 5000; // 5 seconds | |
void setup() | |
{ | |
Serial.begin(115200); | |
WiFi.mode(WIFI_STA); | |
Serial.print("Connecting to "); | |
Serial.print(ssid); | |
WiFi.begin(ssid, password); | |
while (WiFi.status() != WL_CONNECTED) { | |
delay(500); | |
Serial.print("."); | |
} | |
Serial.println("Connected!"); | |
Serial.print("IP Address: "); | |
Serial.println(WiFi.localIP()); | |
} | |
void loop() | |
{ | |
if (millis() - previousMillis > interval) { | |
int err = SimpleDHTErrSuccess; | |
if ((err = dht22.read2(&temperature, &humidity, NULL)) != SimpleDHTErrSuccess) { | |
Serial.print("Read DHT22 failed, err="); Serial.println(err); | |
delay(1000); | |
return; | |
} | |
Serial.print("Sample OK: "); | |
Serial.print((float)temperature); | |
Serial.print(" *C, "); | |
Serial.print((float)humidity); | |
Serial.println(" RH%"); | |
StaticJsonDocument<200> doc; | |
JsonObject root = doc.to<JsonObject>(); // Json Object refer to { } | |
root["device_developer_id"] = DEVICE_DEV_ID; | |
JsonObject data = root.createNestedObject("data"); | |
data["temperature"] = (int)temperature; | |
data["humidity"] = (int)humidity; | |
String body; | |
serializeJson(root, body); | |
Serial.println(body); | |
HTTPClient http; | |
http.begin("http://api.favoriot.com/v1/streams"); | |
http.addHeader("Content-Type", "application/json"); | |
http.addHeader("Apikey", APIKEY); | |
int httpCode = http.POST(body); | |
if (httpCode > 0) { | |
Serial.printf("[HTTP] POST... code: %d\n", httpCode); | |
if (httpCode == HTTP_CODE_OK) { | |
String payload = http.getString(); | |
Serial.println(payload); | |
} | |
} | |
else { | |
Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str()); | |
} | |
http.end(); | |
previousMillis = millis(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment