说明
点亮WS2812 RGB
代码
main/CMakeLists.txt
# 主程序组件
idf_component_register(SRCS "main.c"
INCLUDE_DIRS ".")
CMakeLists.txt
# The following five lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(0_kai_fa_ban)
main/main.c
rmt.h过时了
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/rmt.h"
#include "esp_log.h"
static const char *TAG = "WS2812";
#define WS2812_GPIO_PIN GPIO_NUM_48
#define LED_NUM 1
#define RMT_TX_CHANNEL RMT_CHANNEL_0
// WS2812 timing parameters (in nanoseconds)
#define T0H 350 // 0 bit high time
#define T0L 900 // 0 bit low time
#define T1H 900 // 1 bit high time
#define T1L 350 // 1 bit low time
#define RESET 50000 // Reset time
// Convert time to RMT ticks (80MHz / 4 = 20MHz, 1 tick = 50ns)
#define NS_TO_TICKS(ns) ((ns) / 50)
void ws2812_init(void)
{
rmt_config_t config = RMT_DEFAULT_CONFIG_TX(WS2812_GPIO_PIN, RMT_TX_CHANNEL);
config.clk_div = 4; // 80MHz / 4 = 20MHz
config.mem_block_num = 1;
config.tx_config.loop_en = false;
config.tx_config.carrier_en = false;
config.tx_config.idle_output_en = true;
config.tx_config.idle_level = RMT_IDLE_LEVEL_LOW;
ESP_ERROR_CHECK(rmt_config(&config));
ESP_ERROR_CHECK(rmt_driver_install(config.channel, 0, 0));
ESP_LOGI(TAG, "WS2812 initialized on GPIO %d", WS2812_GPIO_PIN);
}
void set_led_color(uint8_t red, uint8_t green, uint8_t blue)
{
uint8_t color[3] = {green, red, blue}; // WS2812 uses GRB order
rmt_item32_t items[24]; // 3 bytes * 8 bits
// Convert each bit to RMT items
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 8; j++) {
int bit_index = (i * 8) + j;
if (color[i] & (1 << (7 - j))) {
// Bit 1
items[bit_index].level0 = 1;
items[bit_index].duration0 = NS_TO_TICKS(T1H);
items[bit_index].level1 = 0;
items[bit_index].duration1 = NS_TO_TICKS(T1L);
} else {
// Bit 0
items[bit_index].level0 = 1;
items[bit_index].duration0 = NS_TO_TICKS(T0H);
items[bit_index].level1 = 0;
items[bit_index].duration1 = NS_TO_TICKS(T0L);
}
}
}
// Send data
ESP_ERROR_CHECK(rmt_write_items(RMT_TX_CHANNEL, items, 24, true));
// Reset
vTaskDelay(pdMS_TO_TICKS(1));
}
void app_main(void)
{
ESP_LOGI(TAG, "Starting WS2812 Demo");
ws2812_init();
vTaskDelay(pdMS_TO_TICKS(1000));
while (1) {
ESP_LOGI(TAG, "Red");
set_led_color(255, 0, 0);
vTaskDelay(pdMS_TO_TICKS(1000));
ESP_LOGI(TAG, "Green");
set_led_color(0, 255, 0);
vTaskDelay(pdMS_TO_TICKS(1000));
ESP_LOGI(TAG, "Blue");
set_led_color(0, 0, 255);
vTaskDelay(pdMS_TO_TICKS(1000));
ESP_LOGI(TAG, "White");
set_led_color(255, 255, 255);
vTaskDelay(pdMS_TO_TICKS(1000));
ESP_LOGI(TAG, "Off");
set_led_color(0, 0, 0);
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
1924

被折叠的 条评论
为什么被折叠?



