#include <stdio.h>
#include <sdkconfig.h>
#include <driver/ledc.h>
#include <driver/gpio.h>
#include <esp_log.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#define LED_IO 2 //pwm1引脚
#define LED_IO2 4 //pwm2引脚
#define LEDC_MAX_DUTY (1023) //最大占空比,2的13次方
#define LEDC_FADE_TIME 300 //渐变时间
ledc_channel_config_t ledc_con; //声明结构体函数
void ledc_init(void)
{
//设置LED定时器
ledc_timer_config_t ledc_timer =
{
.duty_resolution = LEDC_TIMER_10_BIT, //设置PWM分辨率
.freq_hz = 50 , //设置频率
.speed_mode = LEDC_HIGH_SPEED_MODE,//设置为高速模式
.timer_num = LEDC_TIMER_0,//选择定时器
};
//启动定时器的PWM模式
ledc_timer_config(&ledc_timer);
//LED 灯结构体配置
ledc_con.channel = LEDC_CHANNEL_0;//pwm通道
ledc_con.duty = 0;//占空比
ledc_con.gpio_num = LED_IO; //选择IO口
ledc_con.speed_mode = LEDC_HIGH_SPEED_MODE; //选择高速通道
ledc_con.timer_sel = LEDC_TIMER_0; //选择定时器
ledc_channel_config(&ledc_con);
//安装LED渐变
ledc_fade_func_install(0);
//初始化给舵机默认位置为0度
ledc_set_duty_and_update(LEDC_HIGH_SPEED_MODE,LEDC_CHANNEL_0,77,0);
vTaskDelay(LEDC_FADE_TIME / portTICK_PERIOD_MS);
}
void app_main(void)
{
//选择IO口
esp_rom_gpio_pad_select_gpio(LED_IO);
esp_rom_gpio_pad_select_gpio(LED_IO2);
//设置IO口
gpio_set_direction(LED_IO,GPIO_MODE_OUTPUT);
gpio_set_direction(LED_IO2,GPIO_MODE_OUTPUT);
gpio_set_level(LED_IO2,1);
//定时器、LED灯初始化
ledc_init();
while (1)
{
//逆时针旋转45度
ledc_set_duty_and_update(LEDC_HIGH_SPEED_MODE,LEDC_CHANNEL_0,51,0);
vTaskDelay(LEDC_FADE_TIME / portTICK_PERIOD_MS);
//顺时针时针旋转45度
ledc_set_duty_and_update(LEDC_HIGH_SPEED_MODE,LEDC_CHANNEL_0,102,0);
vTaskDelay(LEDC_FADE_TIME / portTICK_PERIOD_MS);
}
}
评论