#include "pwm.h"
/*******************************************
引脚说明
LED0连接在PF9,低电平灯亮;高电平,灯灭
TIM14_CH3(TIM2 -- APB1 16位 84MHZ)
*******************************************/
void Pwm_PF8_Init(unsigned int psr)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseInitStruct;
TIM_OCInitTypeDef TIM_OCInitStructure;
//使能定时器14
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM13, ENABLE);
//使能GPIOF组时钟
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOF, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;//蜂鸣器的连接该引脚
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用模式
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_25MHz;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP ;
GPIO_Init(GPIOF, &GPIO_InitStructure);
//PF9映射TIM14功能
GPIO_PinAFConfig(GPIOF, GPIO_PinSource8, GPIO_AF_TIM13);
TIM_TimeBaseInitStruct.TIM_Prescaler = (84-1); //84分频 84MHZ/84 = 1MHZ
TIM_TimeBaseInitStruct.TIM_Period = (1000000/psr-1); //计数周期,在1MHZ下,计1000个数,用时1ms
TIM_TimeBaseInitStruct.TIM_CounterMode = TIM_CounterMode_Up; //向上计数
TIM_TimeBaseInitStruct.TIM_ClockDivision= TIM_CKD_DIV1; //分频因子
//2、初始化定时器,配置ARR,PSC。
TIM_TimeBaseInit(TIM13, &TIM_TimeBaseInitStruct);
/* PWM1 Mode configuration: Channel1 */
//通道初始化
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; //PWM1
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //通道使能
TIM_OCInitStructure.TIM_Pulse = 0; //CCR值
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //极性电平,这里设置为低电平
//OC1--通道1
TIM_OC1Init(TIM13, &TIM_OCInitStructure);
//使能预装载寄存器 OC1--通道1
TIM_OC1PreloadConfig(TIM13, TIM_OCPreload_Enable);
//使能自动重装载的预装载寄存器允许位
TIM_ARRPreloadConfig(TIM13, ENABLE);
//使能定时器
TIM_Cmd(TIM13, ENABLE);
}
#include "stm32f4xx.h"
#include "delay.h"
#include "pwm.h"
uint16_t arr[22]={262,294,330,349,392,440,494,523,587,659,698,784,880,988,1047,1175,1319,1397,1568,1760,1967,1000};
int main(void)
{
int count = 0;
int i=0;
//设置NVIC分组(一个项目只能配置一次)
//NVIC第二分组:抢占优先级范围:0~3 响应优先级范围:0~3
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
Delay_Init();//延时初始化
Led_Init();//LED初始化
Key_Init();//按键初始化
Exti_PA0_Init();//外部中断初始化
//不断改变比较值CCRx,达到不同的占空比效果:
//TIM_SetCompare1(TIM14, 800);
while(1)
{
Pwm_PF8_Init(arr[i]);
TIM_SetCompare1(TIM13,arr[i]);
delay_ms(756);
i++;
if(i==7)
{
i=0;
}
}
return 0;
}
STM32通过PWM实现有源蜂鸣器音节奏
于 2023-12-27 20:47:17 首次发布