12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- /**
- * @Author: 李建
- * @Date: 2025/4/22 10:24
- * Description: 蜂鸣器模块
- * Copyright: Copyright (©) 2025 永续绿建. All rights reserved.
- */
- #include "freertos/FreeRTOS.h"
- #include <freertos/event_groups.h>
- #include "beep.h"
- #include "driver/ledc.h"
- #include "esp_err.h"
- #include "main.h"
- #define BEEP_BIT BIT0
- #define STOP_BEEP_BIT BIT1
- static EventGroupHandle_t beep_event_group;
- void beep() {
- xEventGroupSetBits(beep_event_group, BEEP_BIT);
- }
- void beep_stop() {
- xEventGroupSetBits(beep_event_group, STOP_BEEP_BIT);
- }
- static void set_beep() {
- if(system_setting.sound_on_off == 0)return;
- // Set duty to 50%
- ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, system_setting.sound_volume));
- // Update duty to apply the new value
- ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
- }
- static void set_beep_stop() {
- // Stop fading
- ESP_ERROR_CHECK(ledc_set_duty(LEDC_MODE, LEDC_CHANNEL, 0));
- // Update duty to apply the new value
- ESP_ERROR_CHECK(ledc_update_duty(LEDC_MODE, LEDC_CHANNEL));
- }
- static void beep_task(void * arg) {
- for(;;) {
- EventBits_t bits = xEventGroupWaitBits(beep_event_group, BEEP_BIT | STOP_BEEP_BIT, pdTRUE, pdFALSE, portMAX_DELAY);
- if(bits & BEEP_BIT) {
- set_beep();
- vTaskDelay(60 / portTICK_PERIOD_MS);
- set_beep_stop();
- }
- if(bits & STOP_BEEP_BIT) {
- set_beep_stop();
- }
- }
- }
- /**
- * @brief 蜂鸣器模块初始化
- */
- void beep_init(void) {
- ledc_timer_config_t ledc_timer = {
- .speed_mode = LEDC_MODE,
- .timer_num = LEDC_TIMER,
- .duty_resolution = LEDC_DUTY_RES,
- .freq_hz = LEDC_FREQUENCY, // Set output frequency at 4 kHz
- .clk_cfg = LEDC_AUTO_CLK
- };
- ESP_ERROR_CHECK(ledc_timer_config(&ledc_timer));
- ledc_channel_config_t ledc_channel = {
- .speed_mode = LEDC_MODE,
- .channel = LEDC_CHANNEL,
- .timer_sel = LEDC_TIMER,
- .intr_type = LEDC_INTR_DISABLE,
- .gpio_num = LEDC_OUTPUT_IO,
- .duty = 0, // Set duty to 0%
- .hpoint = 0
- };
- ESP_ERROR_CHECK(ledc_channel_config(&ledc_channel));
- beep_event_group = xEventGroupCreate();
- xTaskCreate(beep_task, "beep_task", 2048, NULL, 5, NULL);
- }
|