#include <WiFi.h>
#include "ThingSpeak.h"
// WiFi credentials
const char* ssid = "YOUR_WIFI_NAME";
const char* password = "YOUR_WIFI_PASSWORD";
// ThingSpeak credentials
unsigned long myChannelNumber = YOUR_CHANNEL_ID;
const char * myWriteAPIKey = "YOUR_API_KEY";
// WiFi + ThingSpeak client
WiFiClient client;
// MQ-2 sensor pin
const int gasSensorPin = 34; // ADC pin
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi Connected!");
ThingSpeak.begin(client);
}
void loop() {
// Read gas sensor value
int sensorValue = analogRead(gasSensorPin);
float voltage = sensorValue * (3.3 / 4095.0); // convert ADC to voltage
Serial.print("Gas Sensor Value: ");
Serial.println(sensorValue);
Serial.print("Voltage: ");
Serial.println(voltage);
// Send data to ThingSpeak
int httpCode = ThingSpeak.writeField(myChannelNumber, 1, sensorValue, myWriteAPIKey);
if (httpCode == 200) {
Serial.println("Data sent to ThingSpeak successfully!");
} else {
Serial.println("Error sending data: " + String(httpCode));
}
delay(20000); // ThingSpeak requires at least 15 sec delay
}void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.println("Hello, ESP32!");
}
void loop() {
// put your main code here, to run repeatedly:
delay(10); // this speeds up the simulation
}