stm32f103vet6蜂鸣器音乐
时间: 2023-07-28 09:09:59 浏览: 226
控制无源蜂鸣器发声播放音乐.zip
要在STM32F103VE上播放音乐,可以使用蜂鸣器作为输出设备。以下是一个简单的示例程序,可以在STM32F103VE上播放“Mary Had a Little Lamb”的曲调:
```c
#include "stm32f10x.h"
// 定义曲调
#define NOTE_C4 382
#define NOTE_D4 340
#define NOTE_E4 303
#define NOTE_F4 286
#define NOTE_G4 255
#define NOTE_A4 227
#define NOTE_B4 202
// 定义时间
#define Q 600
#define H 1200
// 定义曲谱
uint16_t melody[] = {
NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4,
NOTE_D4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_G4, NOTE_G4,
NOTE_E4, NOTE_D4, NOTE_C4, NOTE_D4, NOTE_E4, NOTE_E4, NOTE_E4,
NOTE_E4, NOTE_D4, NOTE_D4, NOTE_E4, NOTE_D4, NOTE_C4
};
uint16_t noteDurations[] = {
Q, Q, Q, Q, Q, Q, H,
Q, Q, Q, Q, Q, H,
Q, Q, Q, Q, Q, Q, H,
Q, Q, Q, Q, Q, H
};
void delay_us(uint32_t nus)
{
uint32_t temp;
SysTick->LOAD = 9*nus;
SysTick->VAL = 0;
SysTick->CTRL = 0x01;
do {
temp = SysTick->CTRL;
} while ((temp & 0x01) && (!(temp & (1 << 16))));
SysTick->CTRL = 0x00;
SysTick->VAL = 0;
}
void delay_ms(uint32_t nms)
{
uint32_t temp;
SysTick->LOAD = 9000*nms;
SysTick->VAL = 0;
SysTick->CTRL = 0x01;
do {
temp = SysTick->CTRL;
} while ((temp & 0x01) && (!(temp & (1 << 16))));
SysTick->CTRL = 0x00;
SysTick->VAL = 0;
}
int main(void)
{
// 初始化SysTick定时器
SysTick->CTRL = 0;
SysTick->LOAD = 0xffffff;
SysTick->VAL = 0;
SysTick->CTRL = 5;
// 初始化GPIO口
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);
// 播放曲调
for (int i = 0; i < sizeof(melody) / sizeof(uint16_t); i++) {
uint16_t noteDuration = noteDurations[i];
uint32_t delayTime = noteDuration * 1000 / melody[i];
for (int j = 0; j < delayTime; j++) {
GPIO_SetBits(GPIOC, GPIO_Pin_13);
delay_us(melody[i] / 2);
GPIO_ResetBits(GPIOC, GPIO_Pin_13);
delay_us(melody[i] / 2);
}
delay_ms(noteDuration * 0.3);
}
while (1) {
}
}
```
这个程序使用SysTick定时器来生成延迟,然后使用GPIO口控制蜂鸣器。在循环中,它遍历曲调和持续时间数组,并使用延迟计算出每个音符播放的时间。然后,它使用GPIO口控制蜂鸣器播放音符。
阅读全文