使用stm32f103实现蜂鸣器播放歌曲天外来物
时间: 2023-07-20 14:12:24 浏览: 226
使用STM32F103实现蜂鸣器播放歌曲《天外来物》的代码如下:
```c
#include "stm32f10x.h"
// 定义蜂鸣器引脚
#define BUZZER_PIN GPIO_Pin_0
#define BUZZER_PORT GPIOA
// 定义音符频率
#define C4 262
#define D4 294
#define E4 330
#define F4 349
#define G4 392
#define A4 440
#define B4 494
// 定义每个音符的持续时间
#define QUA 500
#define HAF 1000
#define EIG 125
// 定义歌曲
int song[] = {E4, F4, G4, A4, G4, F4, E4, E4, F4, G4, A4, G4, F4, E4, E4, F4, G4, A4, B4, A4, G4, F4, E4, E4, E4, F4, G4, A4, G4, F4, E4, E4, F4, G4, A4, G4, F4, E4, E4, F4, G4, A4, B4, A4, G4, F4, E4};
// 定义歌曲的时值
int duration[] = {QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, QUA, QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, HAF, QUA, QUA, HAF, QUA, QUA, QUA, QUA, QUA, QUA, QUA, HAF};
// 播放音符
void play_note(int note, int duration) {
int i, t;
t = 1000000 / note;
for (i = 0; i < duration * 1000 / (t * 2); i++) {
GPIO_SetBits(BUZZER_PORT, BUZZER_PIN);
Delay_us(t);
GPIO_ResetBits(BUZZER_PORT, BUZZER_PIN);
Delay_us(t);
}
}
// 延时函数
void Delay_us(u32 nCount) {
u32 i;
for (i = 0; i < nCount * 8; i++);
}
int main(void) {
int i;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = BUZZER_PIN;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(BUZZER_PORT, &GPIO_InitStructure);
while (1) {
for (i = 0; i < sizeof(song) / sizeof(song[0]); i++) {
play_note(song[i], duration[i]);
Delay_us(EIG * 1000);
}
}
}
```
代码中将歌曲《天外来物》的音符与时值分别存储在数组song和duration中,通过play_note函数实现了蜂鸣器的播放功能,并通过Delay_us函数实现了不同音符之间的时间间隔。需要注意的是,蜂鸣器的引脚需要通过GPIO_Init函数进行初始化,才能使蜂鸣器正常工作。
阅读全文