stm32蜂鸣器音乐代码
时间: 2023-07-02 21:03:42 浏览: 66
以下是一个简单的使用STM32蜂鸣器播放音乐的代码:
```c
#include "stm32f10x.h"
#define C 1911
#define D 1703
#define E 1517
#define F 1432
#define G 1276
#define A 1136
#define B 1012
void delay(int ms) {
int i, j;
for (i = 0; i < ms; i++) {
for (j = 0; j < 1000; j++);
}
}
void play(int frequency, int duration) {
int i;
int half_period = 1000000 / (2 * frequency);
int cycles = frequency * duration / 1000;
for (i = 0; i < cycles; i++) {
GPIOC->ODR ^= GPIO_Pin_13;
delay(half_period / 1000);
GPIOC->ODR ^= GPIO_Pin_13;
delay(half_period / 1000);
}
}
int main(void) {
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_13;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOC, &GPIO_InitStructure);
while (1) {
play(C, 200);
delay(50);
play(D, 200);
delay(50);
play(E, 200);
delay(50);
play(F, 200);
delay(50);
play(G, 200);
delay(50);
play(A, 200);
delay(50);
play(B, 200);
delay(50);
}
}
```
该代码使用了GPIOC的13号引脚作为蜂鸣器,播放了简单的音阶。你可以根据自己的需求修改频率和持续时间来播放不同的音乐。