#include "stm32f10x.h" #include "sys.h" static GPIO_InitTypeDef GPIO_InitStructure; static TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;//配置频率 static TIM_OCInitTypeDef TIM_OCInitStructure; //配置占空比 static uint32_t temp=0; #define PB8OUT(n) *(volatile uint32_t *)(0x42000000+((uint32_t)&GPIOB->ODR-0x40000000)*32+n*4) void delay_ms(uint32_t n){ while(n--){ SysTick->CTRL=0; //关闭系统定时器,第0位:使能位,1为使能 SysTick->LOAD=(72000)-1;//配置计数值,因为计算机从0开始,所以减一 SysTick->VAL=0;//清空当前的值(标志位),定时器在计数时,标志位为0,当计数完毕时,标志位为1 SysTick->CTRL=5;//5=101 使能系统计时器,并且使用系统时钟 //第二位:时钟选择位,0=系统时钟/8,1=系统时钟 while((SysTick->CTRL&0x10000)==0);//等待计数到0 //第16位:计数到0则为1 } SysTick->CTRL=0; } void BEEPinit(void){ //蜂鸣器PB8/TIM4_CH3 //使能端口 RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //初始化GPIO引脚 GPIO_InitStructure.GPIO_Pin=GPIO_Pin_8; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;//要用到复用功能,所以把引脚的模式改成复用推挽 GPIO_InitStructure.GPIO_Speed= GPIO_Speed_50MHz;//高速响应 GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_ResetBits(GPIOB,GPIO_Pin_8); } //设置频率 void TIM4init(uint32_t frep){ // 蜂鸣器PB8/TIM4_CH3 //使能定时器4硬件时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); TIM_TimeBaseStructure.TIM_Period = 10000/frep-1;//计数值,决定输出频率为100Hz TIM_TimeBaseStructure.TIM_Prescaler = 7200-1;//预分频器7100-1+1,隐形着一个+1操作,所以要减一 TIM_TimeBaseStructure.TIM_ClockDivision = 0;//这个用不到 TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;//向上计数 TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); temp=TIM_TimeBaseStructure.TIM_Period; 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_OC3Init(TIM4, &TIM_OCInitStructure); TIM_Cmd(TIM4, ENABLE); } //设置占空比 void TIM4_setduty(uint16_t duty){ uint16_t compare=0; compare=(temp+1)*duty/100;//(计数值+1)*占空比 TIM_SetCompare3(TIM4,compare);//由通道决定是几,CH3所以就选Compare3; } int main(){ uint32_t i; uint16_t frep[10]={262,1976,784,494,330,698}; BEEPinit(); while(1){ for(i=0;i<10;i++){ TIM4init(frep[i]); TIM4_setduty(50); delay_ms(1000); } } }
微信扫码关注
更新实时通知