· 5 years ago · Jun 07, 2020, 02:24 PM
1/*
2Problem Statement: Receive data from thingSpeak Channel
3 WiFi Credentials are not hardcoded, They can be updated in real time using Tzapu WiFiManager Library
4Developed by: Rahul Shrivastava
5*********************************
6*/
7
8#include <Arduino.h>//
9#include <ESP8266WiFi.h>
10#include <ESP8266HTTPClient.h>
11#include <DNSServer.h>
12#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
13
14String readAPIkey = "702L9HBEV9F88HHV";// Read API Key of ThingSpeak channel
15String channel_ID = "1024134";
16String field_N = "2";
17String result_N = "1";
18 //"http://api.thingspeak.com/channels/1024134/fields/2.json?api_key=702L9HBEV9F88HHV&results=1"
19
20void setup() {
21 Serial.begin(115200);
22 Serial.flush();
23 pinMode(D0, OUTPUT);
24 wificonnect();
25}
26
27void loop() {
28
29 float temperature = GETreceive();
30 if (temperature>33)
31 {
32 digitalWrite(D0, LOW);
33 }
34 else
35 {
36 digitalWrite(D0, HIGH);
37 }
38}
39
40void wificonnect()
41 {
42 WiFiManager wifiManager;
43 wifiManager.autoConnect("RS_Receiver_Node");
44 Serial.println("connected to RS_receiver_Node:)");
45 }
46
47float GETreceive()
48{
49 HTTPClient http;
50
51 Serial.print("[HTTP] begin...\n");
52
53 //"http://api.thingspeak.com/channels/963373/fields/1.json?api_key=28WYJLR74BJ9ZKAT&results=1"
54 String url = "http://api.thingspeak.com/channels/";
55 url += channel_ID; //
56 url += "/fields/";
57 url += field_N;
58 url += ".json?api_key=";
59 url += readAPIkey;
60 url += "&results=";
61 url += result_N;
62 Serial.println(url);
63 http.begin(url); //HTTP
64
65 Serial.print("[HTTP] GET...\n");
66
67 // start connection and send HTTP header
68 int httpCode = http.GET();
69
70 // httpCode will be negative on error
71
72 if(httpCode > 0) {
73 // HTTP header has been send and Server response header has been handled
74 Serial.printf("[HTTP] GET... code: %d\n", httpCode);
75
76 if(httpCode == HTTP_CODE_OK) {
77 String payload = http.getString();
78 Serial.println(payload);
79
80 int begin_b = payload.indexOf("\"entry_id");
81 String field_data_string = payload.substring(begin_b+25,begin_b+30);
82 float field_data = field_data_string.toFloat();
83 Serial.println(field_data_string);
84 Serial.println(field_data);
85 return(field_data);
86 }
87 }
88 else
89 {
90 Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
91 }
92
93 http.end();
94
95 delay(16000);
96}