CODE

#include
#include

// Wi-Fi credentials
const char* ssid = “GalaxyNET”;
const char* password = “CONNECTME1”;

// ThingSpeak details
const char* server = “http://api.thingspeak.com/update”;
String apiKey = “NXGKYGD9UIXMN3F7”; // Your Write API Key

// Sensor pin (connected to port 32)
const int sensorPin = 32; // MG811 sensor connected to analog pin 32

// Constants for ADC conversion and voltage reference
const float VREF = 3.3; // Reference voltage for ESP32 (3.3V)
const int ADC_MAX = 4095; // Maximum value for 12-bit ADC

// Constants for the CO2 sensor curve (fine-tune based on MG811 characteristics)
const float A = 1000.0; // Example constant (to be tuned from datasheet)
const float B = 1.5; // Example constant (to be tuned from datasheet)

void setup() {
Serial.begin(115200); // Initialize serial communication
pinMode(sensorPin, INPUT); // Set sensor pin as input

// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print(“Connecting to WiFi”);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(“.”);
}
Serial.println(” Connected!”);
}

// Function to convert analog sensor value to PPM for MG811 sensor
float convertToPPM(int analogValue) {
// Convert the analog value to voltage
float voltage = (analogValue / (float)ADC_MAX) * VREF;

// Convert the voltage to PPM using an approximate formula (adjust A and B as needed)
float ppm = A * pow((voltage / VREF), B);

return ppm;
}

void loop() {
// Read sensor data from the MG811 sensor
int sensorValue = analogRead(sensorPin); // For analog sensor like MG811
float co2_ppm = convertToPPM(sensorValue); // Convert analog reading to PPM

Serial.print(“CO2 Level: “);
Serial.print(co2_ppm);
Serial.println(” ppm”);

// Send data to ThingSpeak
if(WiFi.status() == WL_CONNECTED) {
HTTPClient http;

String url = String(server) + “?api_key=” + apiKey + “&field1=” + String(co2_ppm);

http.begin(url); // Initialize HTTP request
int httpCode = http.GET(); // Send the request

if(httpCode > 0) {
String response = http.getString(); // Get response payload
Serial.println(“Data sent to ThingSpeak, response:”);
Serial.println(response);
} else {
Serial.println(“Error in sending data”);
}
http.end(); // Close the connection
} else {
Serial.println(“WiFi Disconnected”);
}

delay(20000); // Wait 20 seconds to send the next update
}

Leave a Comment

Your email address will not be published. Required fields are marked *