基于STM32用Keil实现PWM彩虹灯控制,编写代码
时间: 2024-03-14 11:49:09 浏览: 154
好的,下面是基于STM32用Keil实现PWM彩虹灯控制的代码:
```c
#include "stm32f10x.h"
#define LED_RED_PIN GPIO_Pin_8
#define LED_GREEN_PIN GPIO_Pin_9
#define LED_BLUE_PIN GPIO_Pin_10
#define PWM_FREQUENCY 1000
#define PWM_PERIOD (SystemCoreClock/PWM_FREQUENCY-1)
uint16_t pwm_red = 0;
uint16_t pwm_green = 0;
uint16_t pwm_blue = 0;
void GPIO_Configuration(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = LED_RED_PIN | LED_GREEN_PIN | LED_BLUE_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void PWM_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);
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(TIM3, &TIM_OCInitStructure);
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void NVIC_Configuration(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);
NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);
}
void TIM3_IRQHandler(void)
{
static uint8_t step = 0;
if (TIM_GetITStatus(TIM3, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM3, TIM_IT_Update);
switch (step)
{
case 0:
pwm_red++;
if (pwm_red >= PWM_PERIOD)
{
pwm_red = PWM_PERIOD;
step++;
}
break;
case 1:
pwm_green++;
if (pwm_green >= PWM_PERIOD)
{
pwm_green = PWM_PERIOD;
step++;
}
break;
case 2:
pwm_red--;
if (pwm_red == 0)
{
step++;
}
break;
case 3:
pwm_blue++;
if (pwm_blue >= PWM_PERIOD)
{
pwm_blue = PWM_PERIOD;
step++;
}
break;
case 4:
pwm_green--;
if (pwm_green == 0)
{
step++;
}
break;
case 5:
pwm_red++;
if (pwm_red >= PWM_PERIOD)
{
pwm_red = PWM_PERIOD;
step++;
}
break;
case 6:
pwm_blue--;
if (pwm_blue == 0)
{
step = 0;
}
break;
default:
break;
}
TIM_SetCompare1(TIM3, pwm_red);
TIM_SetCompare2(TIM3, pwm_green);
TIM_SetCompare3(TIM3, pwm_blue);
}
}
int main(void)
{
GPIO_Configuration();
PWM_Configuration();
NVIC_Configuration();
while (1)
{
}
}
```
以上是基于STM32用Keil实现PWM彩虹灯控制的代码,实现了循环变化的彩虹灯效果。希望对您有所帮助。
阅读全文