本文源码已经上传至csdn:
程序源码如下;
1 #define LEDC_IO_0 (2) 2 3 esp_err_t app_main() 4 { 5 ledc_timer_config_t ledc_timer = { 6 //set timer counter bit number 7 .bit_num = LEDC_TIMER_13_BIT, 8 //set frequency of pwm 9 .freq_hz = 5000, 10 //timer mode, 11 .speed_mode = LEDC_HIGH_SPEED_MODE, 12 //timer index 13 .timer_num = LEDC_TIMER_0 14 }; 15 ledc_timer_config(&ledc_timer); 16 17 ledc_channel_config_t ledc_channel = { 18 //set LEDC channel 0 19 .channel = LEDC_CHANNEL_0, 20 //set the duty for initialization.(duty range is 0 ~ ((2**bit_num)-1) 21 .duty = 0, 22 //GPIO number 23 .gpio_num = LEDC_IO_0, 24 //GPIO INTR TYPE, as an example, we enable fade_end interrupt here. 25 .intr_type = LEDC_INTR_FADE_END, 26 //set LEDC mode, from ledc_mode_t 27 .speed_mode = LEDC_HIGH_SPEED_MODE, 28 //set LEDC timer source, if different channel use one timer, 29 //the frequency and bit_num of these channels should be the same 30 .timer_sel = LEDC_TIMER_0 31 }; 32 //set the configuration 33 ledc_channel_config(&ledc_channel); 34 35 //initialize fade service. 36 ledc_fade_func_install(0); 37 38 while(1) { 39 printf("LEDC fade up\n"); 40 ledc_set_fade_with_time(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 1000, 2000); 41 ledc_fade_start(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, LEDC_FADE_NO_WAIT); 42 vTaskDelay(3000 / portTICK_PERIOD_MS); 43 44 printf("LEDC fade down\n"); 45 ledc_set_fade_with_time(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0, 2000); 46 ledc_fade_start(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, LEDC_FADE_NO_WAIT); 47 vTaskDelay(3000 / portTICK_PERIOD_MS); 48 49 /*printf("LEDC set duty without fade\n"); 50 ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 1000); 51 ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0); 52 vTaskDelay(2000 / portTICK_PERIOD_MS); 53 54 printf("LEDC set duty without fade\n"); 55 ledc_set_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0, 0); 56 ledc_update_duty(LEDC_HIGH_SPEED_MODE, LEDC_CHANNEL_0); 57 vTaskDelay(2000 / portTICK_PERIOD_MS);*/ 58 } 59 }
esp_idf中提供 了LEDC来产生pwm信号,LEDC主要是用来做灯控的,因为其比pwm功能更加丰富,说以esp-idf并没有提供pwm相关的模块。
1、5-15行设置一个LEDC计时器,bit_num设置定时器位数,freq_hz设置定时器平率,speed_mode设定工作模式(目前只能设定高速),timer_num表示使用的定时器号(esp32有四个通用的定时器,号数为0~3) 。我们通过调用ledctimerconfig()来完成这一工作,
2、17-33行设置LEDC通道,值得注意的是,esp32有16个通道可以产生脉冲信号,其中通道0~通道7是高速通道,通道8~通道15是低速通道,目前只支持高速通道。duty设置pwm占空比,intr_type设置中断方式。最后通过ledc_channel_config()完成,
3、while循环中是循环输出打印信息,并控制pwm由0~100或者控制pwm由100~0。,其中ledc_set_fade_with_time有四个参数,分别为
(1)speed_mode:目前只支持高速模式,即LEDC_HIGH_SPEED_MODE.
(2)channel:上面定义使用的通道号,0~7。
(3)target_duty:目标占空比,灯亮度的调节靠调节占空比实现,该参数表示占空比将从当前值逐渐变化到该设定值。
(4)max_fade_time_ms:渐变时间。表示等占空变化到设定值所用的时间,单位是ms。
实验现象:
LED等连接到GPIO 2,可以看到LED灯从暗到亮变化,在从亮到暗变化,每次变化时长为2s,并且转换时,minicom上回输出打印信息。