stm32F405RGTx的RGB彩灯代码
时间: 2023-07-02 09:09:11 浏览: 191
以下是一个简单的RGB彩灯代码,基于STM32F405RGTx单片机,使用PWM控制三个LED:
```c
#include "stm32f4xx.h"
#define LED_R_Pin GPIO_Pin_6
#define LED_R_GPIO_Port GPIOC
#define LED_G_Pin GPIO_Pin_8
#define LED_G_GPIO_Port GPIOC
#define LED_B_Pin GPIO_Pin_9
#define LED_B_GPIO_Port GPIOC
void TIM_Config(void)
{
//使能TIM2时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStruct;
/* 填充结构体 */
TIM_TimeBaseInitStruct.TIM_Prescaler = 168 - 1; //分频系数为168-1
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数模式
TIM_TimeBaseInitStruct.TIM_Period = 100 - 1; //自动重载值为100-1,即PWM周期为100us
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1; //时钟分割
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseInitStruct);
/* 配置三个输出通道 */
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1; //PWM模式1
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable; //输出使能
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High; //输出极性高
TIM_OCInitStruct.TIM_Pulse = 0; //初始占空比为0
TIM_OC1Init(TIM2, &TIM_OCInitStruct);
TIM_OC2Init(TIM2, &TIM_OCInitStruct);
TIM_OC3Init(TIM2, &TIM_OCInitStruct);
/* 使能输出比较通道 */
TIM_OC1PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OC2PreloadConfig(TIM2, TIM_OCPreload_Enable);
TIM_OC3PreloadConfig(TIM2, TIM_OCPreload_Enable);
/* 启动定时器 */
TIM_Cmd(TIM2, ENABLE);
}
void LED_Config(void)
{
GPIO_InitTypeDef GPIO_InitStruct;
/* 使能GPIOC时钟 */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC, ENABLE);
/* 配置GPIOC 6,8,9为复用模式 */
GPIO_InitStruct.GPIO_Pin = LED_R_Pin | LED_G_Pin | LED_B_Pin;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP;
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(LED_R_GPIO_Port, &GPIO_InitStruct);
/* 将GPIOC 6,8,9连接到TIM2上 */
GPIO_PinAFConfig(LED_R_GPIO_Port, GPIO_PinSource6, GPIO_AF_TIM2);
GPIO_PinAFConfig(LED_G_GPIO_Port, GPIO_PinSource8, GPIO_AF_TIM2);
GPIO_PinAFConfig(LED_B_GPIO_Port, GPIO_PinSource9, GPIO_AF_TIM2);
}
int main(void)
{
TIM_Config();
LED_Config();
uint16_t r = 0, g = 0, b = 0; //红、绿、蓝三个LED的占空比
while (1)
{
/* 红色渐变 */
for (r = 0; r < 100; r++)
{
TIM_SetCompare1(TIM2, r);
delay(10);
}
/* 绿色渐变 */
for (g = 0; g < 100; g++)
{
TIM_SetCompare2(TIM2, g);
delay(10);
}
/* 蓝色渐变 */
for (b = 0; b < 100; b++)
{
TIM_SetCompare3(TIM2, b);
delay(10);
}
/* 混合颜色 */
for (r = 0; r < 100; r++)
{
TIM_SetCompare1(TIM2, r);
TIM_SetCompare2(TIM2, 100 - r);
delay(10);
}
for (g = 0; g < 100; g++)
{
TIM_SetCompare2(TIM2, g);
TIM_SetCompare3(TIM2, 100 - g);
delay(10);
}
for (b = 0; b < 100; b++)
{
TIM_SetCompare1(TIM2, 100 - b);
TIM_SetCompare3(TIM2, b);
delay(10);
}
}
}
void delay(uint32_t nCount)
{
for (; nCount != 0; nCount--);
}
```
注意:此代码仅供参考,需要根据具体的硬件和需求进行修改。
阅读全文