基于 ESP8266_RTOS_SDK 实现声控灯

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>

#include "driver/gpio.h"
#include "driver/hw_timer.h"

#include "FreeRTOS.h"
#include "freertos/event_groups.h"
#include "rom/ets_sys.h"

#define PIN GPIO_NUM_5

/**
 * @brief 定时器中断函数,检测事件组
 */
void timer_callback(void *arg){
    EventBits_t bit = xEventGroupGetBitsFromISR((EventGroupHandle_t)arg);
    xEventGroupClearBitsFromISR((EventGroupHandle_t)arg, bit);
    static uint8_t num = 0;
    //接收到声音传感器的响应
    if(0x01 == bit){
        //当前LED灭,重新开启,当前LED已经打开,刷新计时
        if(0 == num){
            num = 5;
            gpio_set_level(2, 0);
        }else{
            num = 5;
        }
    }
    
    if(0 < num){
        num--;
    }else{
        gpio_set_level(2, 1);
    }
}
/**
 * @brief 声音模块GPIO中断函数,下降沿触发,事件组置位
 */
void sound_isr(void *arg){
    BaseType_t base;
    xEventGroupSetBitsFromISR((EventGroupHandle_t)arg, 0x01, &base);
}
/**
 * @brief 使用事件组和中断实现声控灯
 * ESP8266      sound
 * D1(GPIO5)    out
 * VCC          VCC
 * GND          GND
 */
void app_main(void){
    EventGroupHandle_t event = xEventGroupCreate();
    gpio_config_t conf;
    conf.pin_bit_mask = 1 << 2;
    conf.mode = GPIO_MODE_OUTPUT;
    conf.intr_type = GPIO_INTR_DISABLE;
    gpio_config(&conf);
    gpio_set_level(2, 1);//板载LED低电平亮

    conf.pin_bit_mask = 1 << PIN;
    conf.mode = GPIO_MODE_INPUT;
    conf.intr_type = GPIO_INTR_NEGEDGE;
    conf.pull_up_en = 1;
    gpio_config(&conf);
    gpio_install_isr_service(0);
    gpio_isr_handler_add(PIN, sound_isr, event);

    hw_timer_init(timer_callback, event);
    hw_timer_set_reload(true);
    hw_timer_set_clkdiv(TIMER_CLKDIV_16);
    hw_timer_set_intr_type(TIMER_EDGE_INT);
    hw_timer_set_load_data((TIMER_BASE_CLK >> hw_timer_get_clkdiv()));//5000000
    hw_timer_enable(true);

    while(1){
        //也可以主任务实现控制逻辑
        // xEventGroupWaitBits(event, 0x01, pdTRUE, pdFALSE, portMAX_DELAY);
        // gpio_set_level(2, 0);
        // for(uint16_t i = 0; i < 1000; i++){
        //     os_delay_us(1000);
        // }
        // gpio_set_level(2, 1);
        os_delay_us(65534);
    }

}
posted @ 2022-09-02 13:25  新世纪摆烂战士  阅读(65)  评论(0编辑  收藏  举报