#include <WiFi.h>
#include "ThingSpeak.h" // always include thingspeak header file after other header files and custom macros
#define WIFI_SSID "Wokwi-GUEST" // replace MySSID with your WiFi network name
#define WIFI_PASSWORD "" // replace MyPassword with your WiFi password
#define SECRET_CH_ID 2107115 // replace 0000000 with your channel number
#define SECRET_WRITE_APIKEY "HTQHBS7VR2P6RXAM" // replace XYZ with your channel write API Key
#define SECRET_READ_APIKEY "PAK7RC5WHG6D89IV"
#define MQ2 32 // define MQ2 analog pin
#define LED 27
WiFiClient client;
unsigned long myChannelNumber = SECRET_CH_ID;
const char * myWriteAPIKey = SECRET_WRITE_APIKEY;
const char * myReadAPIKey = SECRET_READ_APIKEY;
int MQ2_value;
int LED_status;
unsigned long dataMillis = 0;
void setup() {
Serial.begin(115200); //Initialize serial
pinMode(MQ2, INPUT);
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED)
{
Serial.print(".");
delay(300);
}
Serial.println();
Serial.print("Connected with IP: ");
Serial.println(WiFi.localIP());
Serial.println();
ThingSpeak.begin(client); // Initialize ThingSpeak
}
void loop() {
int statusCode = 0;
MQ2_value = analogRead(MQ2);
if (isnan(MQ2_value))
{
Serial.println("Failed to read from MQ-2 sensor!");
return;
}
ThingSpeak.setField(1, MQ2_value);
//ThingSpeak.setField(2, LED);
// Check the status of the read operation to see if it was successful
statusCode = ThingSpeak.readMultipleFields(myChannelNumber, myReadAPIKey) ;
if(statusCode == 200)
{
// Fetch the stored data
LED_status = ThingSpeak.getFieldAsInt(2); // Field 2
//int LED2 = ThingSpeak.getFieldAsInt(3); // Field 3.....8
Serial.println("LED Status: " + String(LED_status));
if(LED_status==1)
{
digitalWrite(LED,HIGH);
}
if(LED_status==0)
{
digitalWrite(LED,LOW);
}
}
else{
Serial.println("Problem reading channel. HTTP error code " + String(statusCode));
}
//////////////////////////////////////////////////////////////////////////////////////////
if (millis() - dataMillis > 15000)
{
Serial.printf("Digital value: %d\n", MQ2_value);
int x = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);
if(x == 200){
Serial.println("Channel update successful.");
}
else {
Serial.println("Problem updating channel. HTTP error code " + String(x));
}
}
}