基于HAL库的stm32控制有源蜂鸣器播放歌曲的代码
时间: 2023-05-15 17:05:07 浏览: 427
基于HAL库的stm32基本实验代码
以下是基于HAL库的stm32控制有源蜂鸣器播放歌曲的代码:
```c
#include "main.h"
#include "stm32f1xx_hal.h"
#define BUZZER_GPIO_PORT GPIOA
#define BUZZER_GPIO_PIN GPIO_PIN_8
void play_tone(uint16_t frequency, uint16_t duration)
{
uint32_t period = 1000000 / frequency;
uint32_t pulse = period / 2;
uint32_t delay_us = duration * 1000 - pulse;
HAL_GPIO_WritePin(BUZZER_GPIO_PORT, BUZZER_GPIO_PIN, GPIO_PIN_SET);
HAL_Delay(pulse);
HAL_GPIO_WritePin(BUZZER_GPIO_PORT, BUZZER_GPIO_PIN, GPIO_PIN_RESET);
HAL_Delay(delay_us);
}
void play_song(void)
{
uint16_t notes[] = {262, 294, 330, 349, 392, 440, 494, 523};
uint16_t durations[] = {500, 500, 500, 500, 500, 500, 500, 500};
for (int i = 0; i < sizeof(notes) / sizeof(notes[0]); i++)
{
play_tone(notes[i], durations[i]);
}
}
int main(void)
{
HAL_Init();
__HAL_RCC_GPIOA_CLK_ENABLE();
GPIO_InitTypeDef GPIO_InitStruct = {0};
GPIO_InitStruct.Pin = BUZZER_GPIO_PIN;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(BUZZER_GPIO_PORT, &GPIO_InitStruct);
while (1)
{
play_song();
HAL_Delay(1000);
}
}
```
希望这个代码对你有所帮助!
阅读全文