MQ4
#include
#include
#include
// Constants
const int gasSensorPin = 32; // MQ-4 analog pin
const float V_REF = 5.0; // Reference voltage
const float R_LOAD = 10.0; // Load resistance in kΩ
const float R_ZERO = 9.83; // Rs in clean air, adjust after calibration
const float a = 116.6020682; // Datasheet constant
const float b = -2.769034857; // Datasheet constant
// Wi-Fi credentials
const char* ssid = "GalaxyNET";
const char* password = "CONNECTME1";
// ThingSpeak channel info
const String apiUrl = "http://api.thingspeak.com/update";
const String apiKey = "KIXTM7EXY1D66X3C";
// Variables
unsigned long lastUpdate = 0;
// Set up Wi-Fi and HTTP client
WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Connecting to Wi-Fi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Connected to Wi-Fi!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
}
void loop() {
checkWiFi();
unsigned long currentMillis = millis();
if (currentMillis - lastUpdate >= 15000) {
lastUpdate = currentMillis;
int rawValue = analogRead(gasSensorPin);
float sensorVoltage = (rawValue / 4095.0) * V_REF;
if (V_REF - sensorVoltage == 0) {
Serial.println("Sensor voltage too high, skipping calculation...");
return;
}
float R_s = (sensorVoltage * R_LOAD) / (V_REF - sensorVoltage);
float methanePPM = a * pow((R_s / R_ZERO), b);
if (methanePPM < 200) methanePPM = 2;
Serial.print("Methane PPM: ");
Serial.println(methanePPM);
sendToThingSpeak(methanePPM);
}
}
void checkWiFi() {
if (WiFi.status() != WL_CONNECTED) {
Serial.println("WiFi disconnected, reconnecting...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("Reconnected to Wi-Fi!");
}
}
void sendToThingSpeak(float methanePPM) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = apiUrl + "?api_key=" + apiKey + "&field1=" + String(methanePPM);
http.begin(client, url);
int httpCode = http.GET();
if (httpCode > 0) {
Serial.println("Data sent successfully to ThingSpeak!");
} else {
Serial.print("HTTP error: ");
Serial.println(httpCode);
}
http.end();
} else {
Serial.println("WiFi not connected.");
}
}
Comments
Post a Comment