#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 button_pin GPIO_NUM_4
#define adc_channel ADC_CHANNEL_6
typedef enum {
EVENT_BUTTON,
EVENT_LDR
} event_type_t;
typedef struct {
event_type_t type;
int value;
} event_msg_t;
QueueHandle_t event_queue;
adc_oneshot_unit_handle_t adc_handle;
void static IRAM_ATTR button_isr(void *args){
BaseType_t hp_task_woken = pdFALSE;
event_msg_t msg = {
.type = EVENT_BUTTON,
.value = 1,
};
xQueueSendFromISR(event_queue, &msg, &hp_task_woken);
if(hp_task_woken){
portYIELD_FROM_ISR();
}
}
void ldr_task(void *args){
int adc_val;
while(1){
adc_oneshot_read(adc_handle,adc_channel,&adc_val);
event_msg_t msg = {
.type = EVENT_LDR,
.value = adc_val,
};
xQueueSend(event_queue,&msg,portMAX_DELAY);
vTaskDelay(pdMS_TO_TICKS(500));
}
}
void main_task(void * args){
event_msg_t msg;
int system_on = 0;
int led_state = 0;
while(1){
if(xQueueReceive(event_queue,&msg,portMAX_DELAY)){
if(msg.type == EVENT_BUTTON){
system_on ^= 1;
printf("system %s\n",system_on ? "ON" : "OFF");
if (!system_on){
led_state = 0;
gpio_set_level(led_pin, led_state);
}
}
else if(msg.type == EVENT_LDR && system_on){
printf("LDR Value : %d\n",msg.value);
if(msg.value < 1500){
led_state = 1;
}
else{
led_state = 0;
}
gpio_set_level(led_pin,led_state);
}
}
}
}
void app_main() {
gpio_config_t led_config = {
.pin_bit_mask = (1ULL<<led_pin),
.mode = GPIO_MODE_OUTPUT,
};
gpio_config(&led_config);
gpio_config_t button_config = {
.pin_bit_mask = (1ULL<<button_pin),
.mode = GPIO_MODE_INPUT,
.pull_up_en = GPIO_PULLUP_ENABLE,
.intr_type = GPIO_INTR_NEGEDGE,
};
gpio_config(&button_config);
event_queue = xQueueCreate(10, sizeof(event_msg_t));
gpio_install_isr_service(0);
gpio_isr_handler_add(button_pin, button_isr, NULL);
adc_oneshot_unit_init_cfg_t adc_cfg = {
.unit_id = ADC_UNIT_1,
};
adc_oneshot_new_unit(&adc_cfg, &adc_handle);
adc_oneshot_chan_cfg_t chan_cfg = {
.atten = ADC_ATTEN_DB_12,
.bitwidth = ADC_BITWIDTH_DEFAULT,
};
adc_oneshot_config_channel(adc_handle,adc_channel, &chan_cfg);
xTaskCreate(main_task, "MAIN TASK", 4096, NULL,10, NULL);
xTaskCreate(ldr_task, "LDR TASK", 4096, NULL,9, NULL);
printf("System Started\n");
}
Loading
esp32-devkit-c-v4
esp32-devkit-c-v4