stm32f103c8t6 定时器1实现呼吸灯
时间: 2023-06-19 13:07:53 浏览: 180
22 PA1 PWM输出呼吸灯_STM32F103_STM32F103C8T6,PWM_PWM呼吸灯_c8t6time1输出PW
5星 · 资源好评率100%
好的,下面是使用定时器1实现呼吸灯的代码:
```c
#include "stm32f10x.h"
uint16_t pwm_value = 0;
uint16_t pwm_dir = 1;
void TIM1_UP_IRQHandler(void)
{
if (TIM_GetITStatus(TIM1, TIM_IT_Update) != RESET)
{
TIM_ClearITPendingBit(TIM1, TIM_IT_Update);
if (pwm_dir == 1)
{
pwm_value++;
if (pwm_value >= 1000) pwm_dir = 0;
}
else
{
pwm_value--;
if (pwm_value == 0) pwm_dir = 1;
}
TIM_SetCompare1(TIM1, pwm_value);
}
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_TIM1, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_TimeBaseInitStruct.TIM_Period = 1000;
TIM_TimeBaseInitStruct.TIM_Prescaler = 71;
TIM_TimeBaseInitStruct.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInitStruct.TIM_RepetitionCounter = 0;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseInitStruct);
TIM_OCInitTypeDef TIM_OCInitStruct;
TIM_OCInitStruct.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStruct.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStruct.TIM_OutputNState = TIM_OutputNState_Disable;
TIM_OCInitStruct.TIM_Pulse = 0;
TIM_OCInitStruct.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OCInitStruct.TIM_OCNPolarity = TIM_OCNPolarity_Low;
TIM_OCInitStruct.TIM_OCIdleState = TIM_OCIdleState_Reset;
TIM_OCInitStruct.TIM_OCNIdleState = TIM_OCNIdleState_Reset;
TIM_OC1Init(TIM1, &TIM_OCInitStruct);
TIM_Cmd(TIM1, ENABLE);
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM1_UP_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE);
while (1);
}
```
这段代码中使用了定时器1的PWM模式,通过改变占空比来控制LED的亮度,实现呼吸灯效果。在定时器1的中断服务函数中,改变PWM占空比的值。
需要注意的是,这段代码中使用的是TIM1,所以需要开启GPIOA和TIM1的时钟。另外,TIM1的通道1对应的是PA8,需要将PA8配置为TIM1的复用输出引脚。
阅读全文