· 6 years ago · Jan 11, 2020, 06:26 PM
1#include <ESP8266WiFi.h>
2String apiKey = "7KD5YDVTN1KIV8SJ"; // Enter your Write API key from ThingSpeak
3const char *ssid = "Sivatcs"; // replace with your wifi ssid and wpa2 key
4const char *pass = "Redbanana123";
5const char* server = "api.thingspeak.com";
6WiFiClient client;
7void setup()
8{
9Serial.begin(115200);
10delay(10);
11Serial.println("Connecting to ");
12Serial.println(ssid);
13WiFi.begin(ssid, pass);
14while (WiFi.status() != WL_CONNECTED)
15{
16delay(500);
17Serial.print(".");
18}
19Serial.println("");
20Serial.println("WiFi connected");
21}
22void loop()
23{
24float h = analogRead(A0);
25if (isnan(h))
26{
27Serial.println("Failed to read from MQ-5 sensor!");
28return;
29}
30
31if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com
32{
33String postStr = apiKey;
34postStr += "&field1=";
35postStr += String(h/1023*100);
36postStr += "r\n";
37client.print("POST /update HTTP/1.1\n");
38client.print("Host: api.thingspeak.com\n");
39client.print("Connection: close\n");
40client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n");
41client.print("Content-Type: application/x-www-form-urlencoded\n");
42client.print("Content-Length: ");
43client.print(postStr.length());
44client.print("\n\n");
45client.print(postStr);
46Serial.print("Gas Level: ");
47Serial.println(h/1023*100);
48Serial.println("Data Send to Thingspeak");
49}
50client.stop();
51Serial.println("Waiting...");
52
53// thingspeak needs minimum 15 sec delay between updates.
54delay(1500);
55}