#define BLYNK_TEMPLATE_ID "TMPL3pJG9SqIb"
#define BLYNK_TEMPLATE_NAME "air "
#define BLYNK_AUTH_TOKEN "Your Auth Token"
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <driver/gpio.h>
#include <driver/adc.h>
#include <esp_adc_cal.h>
#include <dht.h> // Assuming you have a DHT library for ESP-IDF
// --- Configuration ---
#define DHT_PIN 2
#define MQ2_PIN ADC1_CHANNEL_7 // GPIO35 is ADC1 channel 7 (adjust if needed)
#define ADC_VREF 3.3f // Voltage reference of ESP32 ADC
#define ADC_BITS 12 // Resolution of ESP32 ADC (usually 12-bit)
#define THRESHOLD 30000 // Example threshold (will need adjustment for ESP32 ADC)
// --- Global Variables ---
static esp_adc_cal_characteristics_t adc_chars;
// --- Function to initialize ADC ---
void init_adc() {
// Configure ADC
adc1_config_width(ADC_WIDTH_BIT_12);
adc1_config_channel_atten(MQ2_PIN, ADC_ATTEN_DB_11); // Adjust attenuation as needed
// Characterize ADC
esp_adc_cal_characterize(ADC_UNIT_1, ADC_ATTEN_DB_11, ADC_WIDTH_BIT_12, 1100, &adc_chars); // 1100 mV typical VRef
}
int main(void) {
// Initialize DHT sensor
gpio_set_direction(DHT_PIN, GPIO_MODE_INPUT_OUTPUT); // Set as output initially for init
if (dht_init(DHT_PIN, DHT_TYPE_DHT22) != ESP_OK) {
printf("DHT22 initialization failed!\n");
return 1;
}
// Initialize ADC
init_adc();
while (1) {
float temperature = NAN;
float humidity = NAN;
// Read DHT22 sensor
if (dht_read_float(&humidity, &temperature) == ESP_OK) {
float temperature_fahrenheit = (temperature * 9.0 / 5.0) + 32.0;
printf("--- Sensor Readings ---\n");
printf("Temperature: %.1f C (%.1f F)\n", temperature, temperature_fahrenheit);
printf("Humidity: %.1f %%\n", humidity);
} else {
printf("Error reading DHT22 sensor\n");
}
// Read MQ2 gas sensor
uint32_t adc_reading = adc1_get_raw(MQ2_PIN);
float voltage = esp_adc_cal_raw_to_voltage(adc_reading, &adc_chars) / 1000.0f; // Convert mV to V
printf("ADC Reading: %u, Voltage: %.2f V\n", adc_reading, voltage);
// Adjust the threshold for the ESP32 ADC reading
// The raw ADC reading will be between 0 and 4095 (for 12-bit resolution).
// You'll need to determine an appropriate threshold based on your sensor's output.
uint32_t esp32_threshold = (uint32_t)((THRESHOLD / 65535.0) * pow(2, ADC_BITS)); // Scale the Python threshold
if (adc_reading > esp32_threshold) {
printf("Gas detected!\n");
} else {
printf("No gas detected.\n");
}
sleep(2); // Delay for 2 seconds
}
return 0;
}