通过 RMT(Remote Control Transceiver)遥控收发器控制RGB LED
led_strip.h
#ifndef __LED_STRIP_H
#define __LED_STRIP_H
#include "driver/rmt_tx.h"
#include "esp_log.h"
typedef struct {
uint8_t green;
uint8_t red;
uint8_t blue;
} led_color_t;
void led_strip_init(void);
void led_strip_deinit(void);
void led_strip_update(led_color_t color);
#endif
led_strip.c
#include "led_strip.h"
#define STRIP_LEN 1
#define RMT_TX_GPIO 8
static const char *TAG = "LED_STRIP";
static rmt_channel_handle_t rmt_channel_handle;
static rmt_encoder_handle_t rmt_encoder_handle;
/**
* @brief 初始化
*/
void led_strip_init(void)
{
rmt_tx_channel_config_t rmt_tx_channel_config = {
.clk_src = RMT_CLK_SRC_DEFAULT,
.gpio_num = RMT_TX_GPIO,
.resolution_hz = 10 * 1000 * 1000, // 10MHz
.mem_block_symbols = 64,
.trans_queue_depth = 4,
};
ESP_ERROR_CHECK(rmt_new_tx_channel(&rmt_tx_channel_config, &rmt_channel_handle));
// WS2812B
rmt_bytes_encoder_config_t bytes_encoder_config = {
.bit0 = {
.level0 = 1,
.duration0 = 4, // 0.4us
.level1 = 0,
.duration1 = 8, // 0.8us
},
.bit1 = {
.level0 = 1,
.duration0 = 8, // 0.8us
.level1 = 0,
.duration1 = 4, // 0.4us
},
};
ESP_ERROR_CHECK(rmt_new_bytes_encoder(&bytes_encoder_config, &rmt_encoder_handle));
rmt_enable(rmt_channel_handle);
}
/**
* @brief 反初始化
*/
void led_strip_deinit(void)
{
rmt_del_channel(rmt_channel_handle);
rmt_del_encoder(rmt_encoder_handle);
}
/**
* @brief 设置颜色
*/
void led_strip_update(led_color_t color)
{
ESP_LOGI(TAG, "set color (%d, %d, %d)", color.red, color.green, color.blue);
led_color_t color_buffer[STRIP_LEN] = {color};
rmt_transmit_config_t rmt_transmit_config = {
.loop_count = 0
};
ESP_ERROR_CHECK(rmt_transmit(rmt_channel_handle, rmt_encoder_handle,
&color_buffer, sizeof(color_buffer), &rmt_transmit_config));
rmt_tx_wait_all_done(rmt_channel_handle, 0xFF);
}
浙公网安备 33010602011771号