In Progress
Lesson 1, Topic 1
In Progress

5.5 Code

26/07/2021

Steps to do coding in Arduino IDE

1. Open Arduino IDE.

2. For writing this code, add the Esp8266WIFI.h library.

Here is a program for Air Quality Monitoring project. Copy this code and upload it to Nodemcu.

Note: Change the wifi SSID, password, and thingspeak API key.

Complete Code:

#include
String apiKey = “Your API key in thingpeak”; // Enter your Write API key from ThingSpeak
const char *ssid = “Your SSID name”; // replace with your wifi ssid and wpa2 key
const char *pass = “Your password”;
const char* server = “api.thingspeak.com”;

WiFiClient client;
void setup()
{
Serial.begin(115200);
delay(10);
Serial.println(“Connecting to “);
Serial.println(ssid);
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(“.”);
}
Serial.println(“”);
Serial.println(“WiFi connected”);
}
void loop()
{
float air_quality = analogRead(A0);


if (client.connect(server, 80)) // “184.106.153.149” or api.thingspeak.com
{
String postStr = apiKey;
postStr += “&field1=”;
postStr += String(air_quality/1023*100);
postStr += “r\n”;
client.print(“POST /update HTTP/1.1\n”);
client.print(“Host: api.thingspeak.com\n”);
client.print(“Connection: close\n”);
client.print(“X-THINGSPEAKAPIKEY: ” + apiKey + “\n”);
client.print(“Content-Type: application/x-www-form-urlencoded\n”);
client.print(“Content-Length: “);
client.print(postStr.length());
client.print(“\n\n”);
client.print(postStr);
Serial.print(“Air quality Level: “);
Serial.println(air_quality/1023*100);
Serial.println(“Data Send to Thingspeak”);
}
delay(500);
client.stop();
Serial.println(“Waiting…”);

// thingspeak needs minimum 15 sec delay between updates.
delay(1500);
}