ESP32用SDK创建用LED PWM控制器实现通过更改0xFFFFFF值来更改RGB颜色的代码
时间: 2024-05-22 14:16:11 浏览: 102
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "driver/ledc.h"
#define LED_RED_GPIO 22
#define LED_GREEN_GPIO 21
#define LED_BLUE_GPIO 19
#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 LEDC_TIMER_BIT LEDC_TIMER_13_BIT
#define MAX_DUTY_CYCLE ((1<<LEDC_TIMER_BIT)-1)
void pwm_init()
{
ledc_timer_config_t ledc_timer = {
.duty_resolution = LEDC_TIMER_BIT,
.freq_hz = 5000,
.speed_mode = LEDC_MODE,
.timer_num = LEDC_TIMER
};
ledc_timer_config(&ledc_timer);
ledc_channel_config_t ledc_channel_red = {
.channel = LEDC_CHANNEL_RED,
.duty = 0,
.gpio_num = LED_RED_GPIO,
.speed_mode = LEDC_MODE,
.timer_sel = LEDC_TIMER
};
ledc_channel_config(&ledc_channel_red);
ledc_channel_config_t ledc_channel_green = {
.channel = LEDC_CHANNEL_GREEN,
.duty = 0,
.gpio_num = LED_GREEN_GPIO,
.speed_mode = LEDC_MODE,
.timer_sel = LEDC_TIMER
};
ledc_channel_config(&ledc_channel_green);
ledc_channel_config_t ledc_channel_blue = {
.channel = LEDC_CHANNEL_BLUE,
.duty = 0,
.gpio_num = LED_BLUE_GPIO,
.speed_mode = LEDC_MODE,
.timer_sel = LEDC_TIMER
};
ledc_channel_config(&ledc_channel_blue);
ledc_fade_func_install(0);
}
void set_color(uint32_t color)
{
uint8_t r = (color >> 16) & 0xFF;
uint8_t g = (color >> 8) & 0xFF;
uint8_t b = color & 0xFF;
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_RED, (r * MAX_DUTY_CYCLE) / 255);
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_GREEN, (g * MAX_DUTY_CYCLE) / 255);
ledc_set_duty(LEDC_MODE, LEDC_CHANNEL_BLUE, (b * MAX_DUTY_CYCLE) / 255);
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 app_main()
{
pwm_init();
while (1) {
set_color(0xFF0000); // Red
vTaskDelay(1000 / portTICK_PERIOD_MS);
set_color(0x00FF00); // Green
vTaskDelay(1000 / portTICK_PERIOD_MS);
set_color(0x0000FF); // Blue
vTaskDelay(1000 / portTICK_PERIOD_MS);
set_color(0xFFFFFF); // White
vTaskDelay(1000 / portTICK_PERIOD_MS);
}
}
阅读全文