用keil5点亮WB2812RGB灯带
时间: 2023-12-10 15:20:15 浏览: 113
基于STC系列51单片机WS2812驱动代码KEIL5工程文件.zip
5星 · 资源好评率100%
要用 Keil5 点亮 WS2812B RGB 灯带,需要连接单片机和 WS2812B 灯带,然后通过 Keil5 编写程序,控制单片机的输出口来控制 WS2812B 灯带的亮度和颜色。以下是一个简单的代码示例,可以通过 Keil5 控制 WS2812B RGB 灯带:
```C
#include <stm32f4xx.h>
#include <string.h>
#define LED_NUMBER 8
#define LED_BYTES (LED_NUMBER * 3)
#define LED_PIN GPIO_Pin_12
#define LED_PORT GPIOB
void GPIO_Configuration(void);
void TIM_Configuration(void);
void Send_LED_Data(uint8_t *led_data);
int main(void)
{
uint8_t led_data[LED_BYTES] = {0};
uint8_t color[3] = {0, 0, 0};
uint8_t i;
GPIO_Configuration();
TIM_Configuration();
while(1)
{
// 设置颜色值
color[0] = 0x80; // 红色通道
color[1] = 0x00; // 绿色通道
color[2] = 0x00; // 蓝色通道
// 将颜色值写入 LED 数据
for(i = 0; i < LED_NUMBER; i++)
{
memcpy(&led_data[i * 3], color, 3);
}
// 发送 LED 数据
Send_LED_Data(led_data);
// 延时
Delay(500);
}
}
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(LED_PORT, &GPIO_InitStructure);
GPIO_PinAFConfig(LED_PORT, GPIO_PinSource12, GPIO_AF_TIM1);
}
void TIM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
uint16_t Period = 89;
uint16_t Prescaler = 6;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE);
TIM_TimeBaseStructure.TIM_Period = Period;
TIM_TimeBaseStructure.TIM_Prescaler = Prescaler;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCStructInit(&TIM_OCInitStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_ARRPreloadConfig(TIM1, ENABLE);
TIM_Cmd(TIM1, ENABLE);
}
void Send_LED_Data(uint8_t *led_data)
{
uint16_t i;
uint8_t data;
__disable_irq(); // 关闭中断
for(i = 0; i < LED_BYTES; i++)
{
data = led_data[i];
__asm("cpsid i"); // 关闭 IRQ 中断
TIM1->CCR1 = 0;
Delay(2);
for(uint8_t j = 0; j < 8; j++)
{
if(data & 0x80)
{
TIM1->CCR1 = 63;
Delay(1);
TIM1->CCR1 = 0;
Delay(2);
}
else
{
TIM1->CCR1 = 63;
Delay(1);
TIM1->CCR1 = 0;
Delay(1);
}
data <<= 1;
}
}
__enable_irq(); // 开启中断
}
void Delay(__IO uint32_t nCount)
{
while(nCount--)
{
}
}
```
以上代码将点亮 8 个 WS2812B RGB 灯,每个灯都设置为红色。你需要根据自己的硬件连接情况修改代码中的引脚定义和 GPIO、定时器初始化部分,以及调整 WS2812B 灯带的颜色和亮度。
阅读全文