stm32 定时器输出pwm 蜂鸣器

尼玛,找了半天居然没几篇文章好使,最重要是要有计算方法,看我的:

void init(void){
GPIO_InitTypeDef GPIO_InitStructure;

RCC->APB1ENR |= RCC_APB1Periph_TIM4; // 使用TIM4_CH3->PB8
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOB, &GPIO_InitStructure);
}


/* hz=2000,period=500;hz=1000,period=1000 */
void beep(int hz)
{
	TIM_TimeBaseInitTypeDef  TIM_TimeBaseStructure;
    TIM_OCInitTypeDef TIM_OCInitStructure;

	TIM_Cmd(TIM4, DISABLE);

	TIM_TimeBaseStructInit(&TIM_TimeBaseStructure);
    TIM_TimeBaseStructure.TIM_Prescaler = 71;  // clock=1mhz
    TIM_TimeBaseStructure.TIM_Period = 1000000/hz; // update = 1Mhz / hz = period
    TIM_TimeBaseStructure.TIM_ClockDivision = 0;
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
    TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure);

    /* Channel1 configuration: PWM2 Mode  */
    TIM_OCStructInit(&TIM_OCInitStructure);
    TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
    TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; 
    TIM_OCInitStructure.TIM_OCPolarity = TIM_OCNPolarity_High;
	TIM_OCInitStructure.TIM_Pulse = (TIM_TimeBaseStructure.TIM_Period+1)*50/100; /* duty = pulse/(period+1),
	                                pulse=50%*(TIM_TimeBaseStructure.TIM_Period+1) */
    TIM_OC3Init(TIM4, &TIM_OCInitStructure);
	TIM_OC3PreloadConfig(TIM4, TIM_OCPreload_Enable);

	TIM_ARRPreloadConfig(TIM4, ENABLE);
	TIM_Cmd(TIM4, ENABLE);
}

void beep_onoff(int is_on)
{
	if(is_on)
		TIM_Cmd(TIM4, ENABLE);
	else
		TIM_Cmd(TIM4, DISABLE);
}

调用:

	/* beep */
	beep(2000);
	OSTimeDly(30);
	beep_onoff(0);
	OSTimeDly(40);
	beep(1600);
	OSTimeDly(50);
	beep(1800);
	OSTimeDly(10);

	beep(2000);
	OSTimeDly(30);
	beep_onoff(0);


本文为3YL原创,转载无需联系,但请注明来自labisart.com。

原创文章不易,如果觉得有帮助,可打赏或点击右侧广告支持:

查看打赏记录

发表评论请遵守党国法律!后台审核后方可显示!
  • 最新评论
  • 总共0条评论
  • Blog v1.1© 2024 labisart.com 版权所有 | 联系:labartwork@163.com