ESP32用SDK创建RGB的PWM七彩渐变程序
时间: 2024-05-09 09:20:16 浏览: 161
七彩LED渐变程序
5星 · 资源好评率100%
以下是使用ESP32 SDK创建RGB PWM七彩渐变程序的示例代码:
```c
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#define RED_PIN GPIO_NUM_18
#define GREEN_PIN GPIO_NUM_19
#define BLUE_PIN GPIO_NUM_21
#define LEDC_TIMER LEDC_TIMER_0
#define LEDC_MODE LEDC_HIGH_SPEED_MODE
#define LEDC_CHANNEL_RED LEDC_CHANNEL_0
#define LEDC_CHANNEL_GREEN LEDC_CHANNEL_1
#define LEDC_CHANNEL_BLUE LEDC_CHANNEL_2
#define PWM_FREQ 5000
#define PWM_RESOLUTION LEDC_TIMER_10_BIT
#define COLOR_CHANGE_DELAY_MS 10
typedef struct {
uint8_t r;
uint8_t g;
uint8_t b;
} rgb_t;
void ledc_init(void)
{
ledc_timer_config_t timer_conf = {
.duty_resolution = PWM_RESOLUTION,
.freq_hz = PWM_FREQ,
.speed_mode = LEDC_MODE,
.timer_num = LEDC_TIMER,
.clk_cfg = LEDC_AUTO_CLK,
};
ledc_timer_config(&timer_conf);
ledc_channel_config_t channel_conf = {
.channel = LEDC_CHANNEL_RED,
.duty = 0,
.gpio_num = RED_PIN,
.speed_mode = LEDC_MODE,
.timer_sel = LEDC_TIMER,
};
ledc_channel_config(&channel_conf);
channel_conf.channel = LEDC_CHANNEL_GREEN;
channel_conf.gpio_num = GREEN_PIN;
ledc_channel_config(&channel_conf);
channel_conf.channel = LEDC_CHANNEL_BLUE;
channel_conf.gpio_num = BLUE_PIN;
ledc_channel_config(&channel_conf);
}
void set_color_rgb(rgb_t color)
{
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_RED, color.r);
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_GREEN, color.g);
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_BLUE, color.b);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL_RED);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL_GREEN);
ledc_update_duty(LEDC_MODE, LEDC_CHANNEL_BLUE);
}
void rainbow(void)
{
rgb_t color = {255, 0, 0};
int step = 1;
while (1) {
set_color_rgb(color);
color.r -= step;
color.g += step;
if (color.r == 0 && color.g == 255) {
step = -1;
}
if (color.r == 255 && color.g == 0) {
step = 1;
}
vTaskDelay(COLOR_CHANGE_DELAY_MS / portTICK_PERIOD_MS);
}
}
void app_main(void)
{
ledc_init();
xTaskCreate(rainbow, "rainbow", 2048, NULL, 5, NULL);
}
```
该程序使用LEDC模块控制RGB LED的PWM输出,实现了七彩渐变效果。在`ledc_init()`函数中,我们配置了一个10位的PWM定时器,并分别配置了红、绿、蓝三个通道的输出管脚和频率、模式等参数。在`set_color_rgb()`函数中,我们设置了RGB三个通道的占空比,并更新了PWM输出。在`rainbow()`任务中,我们使用循环来改变RGB的值,从而实现了渐变效果。最后,在`app_main()`函数中创建了一个任务来执行`rainbow()`函数。
注意:在使用LEDC模块时,需要先调用`ledc_timer_config()`和`ledc_channel_config()`函数进行配置,然后才能使用`ledc_set_duty()`和`ledc_update_duty()`函数设置和更新PWM输出。在本例中,我们在`ledc_init()`函数中进行了配置。
阅读全文