#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "driver/gpio.h"
#include "esp_adc/adc_oneshot.h"
#define led_pin GPIO_NUM_2
#define channel_S1 ADC_CHANNEL_6
#define channel_S2 ADC_CHANNEL_7
#define channel_S3 ADC_CHANNEL_4
typedef struct {
int s1;
int s2;
int s3;
} get_raw_t;
typedef struct {
int alert;
int sensor_id;
} get_process_t;
QueueHandle_t raw_queue;
QueueHandle_t proc_queue;
adc_oneshot_unit_handle_t adc_handle;
void gas_task(void *args){
get_raw_t data;
while(1){
adc_oneshot_read(adc_handle,channel_S1,&data.s1);
adc_oneshot_read(adc_handle,channel_S2,&data.s2);
adc_oneshot_read(adc_handle,channel_S3,&data.s3);
xQueueSend(raw_queue,&data,portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(500));
}
}
void process_task(void *args){
get_raw_t raw;
get_process_t result;
while(1){
if(xQueueReceive(raw_queue,&raw,portMAX_DELAY)){
printf("S1 : %d, S2 : %d, S2 : %d\n",raw.s1, raw.s2, raw.s3);
result.alert = 0;
result.sensor_id = 0;
if (raw.s1 > 2000){
result.alert = 1;
result.sensor_id = 1;
}
else if (raw.s2 > 2000){
result.alert = 1;
result.sensor_id = 2;
}
else if (raw.s3 > 2000){
result.alert = 1;
result.sensor_id = 3;
}
xQueueSend(proc_queue,&result,portMAX_DELAY);
}
}
}
void alarm_task(void *args){
get_process_t msg;
while(1){
if(xQueueReceive(proc_queue,&msg,portMAX_DELAY)){
if(msg.alert){
printf("GAS DETECTED at Sensor %d\n",msg.sensor_id);
gpio_set_level(led_pin,1);
}
else{
gpio_set_level(led_pin,0);
}
}
}
}
void app_main() {
gpio_config_t led_config = {
.pin_bit_mask = (1ULL<<led_pin),
.mode = GPIO_MODE_OUTPUT,
};
gpio_config(&led_config);
raw_queue = xQueueCreate(10,sizeof(get_raw_t));
proc_queue = xQueueCreate(10,sizeof(get_process_t));
adc_oneshot_unit_init_cfg_t init_config = {
.unit_id = ADC_UNIT_1,
};
adc_oneshot_new_unit(&init_config, &adc_handle);
adc_oneshot_chan_cfg_t chan_config = {
.atten = ADC_ATTEN_DB_12,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
adc_oneshot_config_channel(adc_handle,channel_S1,&chan_config);
adc_oneshot_config_channel(adc_handle,channel_S2,&chan_config);
adc_oneshot_config_channel(adc_handle,channel_S3,&chan_config);
xTaskCreate(gas_task,"Gas Measurement", 4096, NULL, 10, NULL);
xTaskCreate(process_task,"Gas Process", 4096, NULL, 9, NULL);
xTaskCreate(alarm_task,"Gas Alarm", 2048, NULL, 8, NULL);
printf("System Started\n");
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4