GPIO的PWM
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
//GPIO和定时器初始化
void Ledc_tim_init(){
ledc_channel_config_t ledc_config = {
.gpio_num = 12, /*!< the LEDC output gpio_num, if you want to use gpio16, gpio_num = 16 */
.speed_mode = LEDC_LOW_SPEED_MODE, /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */
.channel = LEDC_CHANNEL_0, /*!< LEDC channel (0 - 7) */
.intr_type = LEDC_INTR_DISABLE, /*!< configure interrupt, Fade interrupt enable or Fade interrupt disable */
.timer_sel = LEDC_TIMER_0, /*!< Select the timer source of channel (0 - 3) */
.duty = 0, /*!< LEDC channel duty, the range of duty setting is [0, (2**duty_resolution)] */
.hpoint = 0, /*!< LEDC channel hpoint value, the max value is 0xfffff */
};
ledc_channel_config(&ledc_config);
const ledc_timer_config_t ledc_timer = {
.speed_mode = LEDC_LOW_SPEED_MODE, /*!< LEDC speed speed_mode, high-speed mode or low-speed mode */
.duty_resolution = LEDC_TIMER_8_BIT, /*!< LEDC channel duty resolution */
.timer_num = LEDC_TIMER_0, /*!< The timer source of channel (0 - 3) */
.freq_hz = 5000, /*!< LEDC timer frequency (Hz) */
.clk_cfg = LEDC_AUTO_CLK,
};
ledc_timer_config(&ledc_timer);
}
//把上面的函数收进下面的函数,统称初始化
void led_init(){
Ledc_tim_init();
ledc_fade_func_install(0);
}
//设置pwm
void user_led_set_duty(uint8_t duty){
ledc_set_duty(ledc_config.speed_mode,ledc_config.channel,255-duty);
ledc_update_duty(ledc_config.speed_mode,ledc_config.channel);
}
void key_scan(void *ptr){
led_init();
gpio_set_direction(GPIO_NUM_9,GPIO_MODE_INPUT);
while(1){
user_led_set_duty(200);
vTaskDelay(1000/portTICK_PERIOD_MS);
}
}
void app_main(void){
xTaskCreate(key_scan,"scan_name",2048,NULL,2,NULL);
}