ESP32之PWM控制LED呼吸

@fsw  October 9, 2018
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/ledc.h"
#include "esp_err.h"

#define LEDC_HS_TIMER          LEDC_TIMER_0
#define LEDC_HS_MODE           LEDC_HIGH_SPEED_MODE//高速模式
#define LEDC_HS_CH0_GPIO       (18)
#define LEDC_HS_CH0_CHANNEL    LEDC_CHANNEL_0

#define LEDC_LS_TIMER          LEDC_TIMER_1
#define LEDC_LS_MODE           LEDC_LOW_SPEED_MODE//低速模式

#define LEDC_TEST_CH_NUM       (1) //通道数
#define LEDC_TEST_DUTY         (4000) 
#define LEDC_TEST_FADE_TIME    (3000)
/*
*1.配置定时器:ledc_timer_config(),ledc_timer_config_t提供参数结构
*2.配置频道:ledc_channel_config(),ledc_channel_config_t提供参数结构
*3.更改pwm信号:
*       a.用软件更改:先调用ledc_set_duty(),然后调用ledc_update_duty()使更改生效
*       b.用硬件更改:需要先启用淡入淡出函数ledc_fade_func_install(),让后调用以下函数配置
*         ledc_set_fade_with_time(),ledc_set_fade_with_step(),ledc_set_fade() 
*         开始ledc_set_start(),不需要了就ledc_fade_uninstall().
*/
void app_main()
{
    int ch;
   //led定时器参数配置
    ledc_timer_config_t ledc_timer = {
        .duty_resolution = LEDC_TIMER_13_BIT, // resolution of PWM 分辨率
        .freq_hz = 5000,                      // pwm信号频率
        .speed_mode = LEDC_HS_MODE,           // 定时器模式
        .timer_num = LEDC_HS_TIMER            // 定时器索引
    };
    //配置好结构体后调用,参数为上面的结构体
    ledc_timer_config(&ledc_timer);

    // 低速通道 timer1 的制备与设置
    ledc_timer.speed_mode = LEDC_LS_MODE;
    ledc_timer.timer_num = LEDC_LS_TIMER;
    ledc_timer_config(&ledc_timer);

    ledc_channel_config_t ledc_channel[LEDC_TEST_CH_NUM] = {
        {
            .channel    = LEDC_HS_CH0_CHANNEL,
            .duty       = 0,
            .gpio_num   = LEDC_HS_CH0_GPIO,
            .speed_mode = LEDC_HS_MODE,
            .timer_sel  = LEDC_HS_TIMER
        },

    };
    // 使用以前准备好的配置设置 LED 控制器
        ledc_channel_config(&ledc_channel[0]);
    //初始化淡入淡出服务。
    ledc_fade_func_install(0);
    while (1) {
        printf("1. LEDC fade up to duty = %d\n", LEDC_TEST_DUTY);
            ledc_set_fade_with_time(ledc_channel[0].speed_mode,
                    ledc_channel[0].channel, LEDC_TEST_DUTY, LEDC_TEST_FADE_TIME);
            ledc_fade_start(ledc_channel[0].speed_mode,
                    ledc_channel[0].channel, LEDC_FADE_NO_WAIT);
        vTaskDelay(LEDC_TEST_FADE_TIME / portTICK_PERIOD_MS);
       printf("2. LEDC fade down to duty = 0\n");
            ledc_set_fade_with_time(ledc_channel[0].speed_mode,
                    ledc_channel[0].channel, 0, LEDC_TEST_FADE_TIME);
            ledc_fade_start(ledc_channel[0].speed_mode,
                    ledc_channel[0].channel, LEDC_FADE_NO_WAIT);
        vTaskDelay(LEDC_TEST_FADE_TIME / portTICK_PERIOD_MS);
    }
}
阅读量:720

添加新评论