- 项目:stm32 输出PWM实现呼吸灯效果
- 代码:
- PWM.c
#include "stm32f10x.h" void PWM_Init(void) { //PB0默认TIM3_CH3通道 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); //配置PB0为复用推挽输出 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出,中断控制来自片上外设(TIM3_CH3),而非输出数据寄存器 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); //设置TIM3定时器内部时钟源 TIM_InternalClockConfig(TIM3); //频率为1kHz, 占空比为50%,分辨率为1% TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStructure; TIM_TimeBaseInitStructure.TIM_ClockDivision = TIM_CKD_DIV1; TIM_TimeBaseInitStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInitStructure.TIM_Period = 100 - 1; //ARR TIM_TimeBaseInitStructure.TIM_Prescaler = 720 - 1; //PSC TIM_TimeBaseInitStructure.TIM_RepetitionCounter = 0; TIM_TimeBaseInit(TIM3, &TIM_TimeBaseInitStructure); //清除更新标志位 TIM_ClearFlag(TIM3, TIM_FLAG_Update); TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE); //TIM3中断配置使能 TIM_OCInitTypeDef TIM_OCInitStructure; TIM_OCStructInit(&TIM_OCInitStructure); //给结构体赋初始值 TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //输出比较模式 TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //极性选择 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //输出使能 TIM_OCInitStructure.TIM_Pulse = 0; //CCR TIM_OC3Init(TIM3, &TIM_OCInitStructure); //打开TIM3定时器外设 TIM_Cmd(TIM3, ENABLE); } //PWM占空比的函数 void PWM_SetCompare3(uint16_t Compare3) { TIM_SetCompare3(TIM3, Compare3); }
- PWM.h
#ifndef __PWM_H #define __PWM_H void PWM_Init(void); void PWM_SetCompare3(uint16_t Compare3); #endif
- main.c
#include "stm32f10x.h" #include "Delay.h" #include "OLED.h" #include "PWM.h" uint8_t i; int main(void) { PWM_Init(); //PWM初始化 while(1) { for(i = 0; i <= 100; i ++) { PWM_SetCompare3(i); //设置TIM3捕获比较3寄存器的值,即CRR Delay_ms(10); } for(i = 0; i <= 100; i ++) { PWM_SetCompare3(100 - i); Delay_ms(10); } } }
- PWM.c
- 参考资料
-