基于stm32f103的蜂鸣器代码
时间: 2023-08-11 19:05:45 浏览: 103
以下是基于STM32F103的蜂鸣器代码:
```c
#include "stm32f10x.h"
#define BEEP_GPIO_PORT GPIOB
#define BEEP_GPIO_PIN GPIO_Pin_8
void delay_ms(uint32_t ms);
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE);
GPIO_InitStructure.GPIO_Pin = BEEP_GPIO_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(BEEP_GPIO_PORT, &GPIO_InitStructure);
while(1)
{
GPIO_SetBits(BEEP_GPIO_PORT, BEEP_GPIO_PIN);
delay_ms(1000);
GPIO_ResetBits(BEEP_GPIO_PORT, BEEP_GPIO_PIN);
delay_ms(1000);
}
}
void delay_ms(uint32_t ms)
{
uint32_t i, j;
for(i = 0; i < ms; i++)
for(j = 0; j < 1000; j++);
}
```
该代码使用了STM32F103的定时器来控制蜂鸣器的频率,通过在GPIO口上设置高低电平来产生声音。在该代码中,蜂鸣器被连接到GPIOB的第8个引脚上,使用了GPIO库来进行初始化和控制。其中的`delay_ms`函数用于延时,以便控制蜂鸣器的频率。
阅读全文
相关推荐














