帮我写一段msp430f149蜂鸣器播放祝你平安歌的代码
时间: 2023-05-24 12:04:43 浏览: 143
单片机唱歌---“祝你平安”(源码)
下面是使用msp430f149驱动蜂鸣器播放“祝你平安”歌曲的代码:
```
#include <msp430f149.h>
// 祝你平安歌曲的音符频率,单位Hz
#define PING_AN_NOTE1 523
#define PING_AN_NOTE2 587
#define PING_AN_NOTE3 659
#define PING_AN_NOTE4 698
#define PING_AN_NOTE5 784
#define PING_AN_NOTE6 880
// 定义时长函数,单位ms
#define BEAT_DURATION 500
#define SHORT_BEAT (BEAT_DURATION / 2)
#define LONG_BEAT (BEAT_DURATION * 2)
// 蜂鸣器引脚设置
#define BUZZER_PIN BIT4
#define BUZZER_PORT P3OUT
// 蜂鸣器控制函数
void buzzerOn(int duration_ms) {
BUZZER_PORT |= BUZZER_PIN;
__delay_cycles(duration_ms * 1000);
BUZZER_PORT &= ~BUZZER_PIN;
}
void playPingAnSong() {
while (1) {
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(LONG_BEAT);
__delay_cycles(LONG_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 400);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(LONG_BEAT);
__delay_cycles(LONG_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 800);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(LONG_BEAT);
__delay_cycles(LONG_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(SHORT_BEAT);
__delay_cycles(SHORT_BEAT * 800);
buzzerOn(PING_AN_NOTE2);
__delay_cycles(SHORT_BEAT * 500);
buzzerOn(PING_AN_NOTE4);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(PING_AN_NOTE5);
__delay_cycles(SHORT_BEAT * 300);
buzzerOn(PING_AN_NOTE6);
__delay_cycles(SHORT_BEAT * 500);
buzzerOn(PING_AN_NOTE5);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(PING_AN_NOTE4);
__delay_cycles(SHORT_BEAT * 300);
buzzerOn(PING_AN_NOTE3);
__delay_cycles(SHORT_BEAT * 500);
buzzerOn(PING_AN_NOTE1);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(PING_AN_NOTE2);
__delay_cycles(SHORT_BEAT * 300);
buzzerOn(PING_AN_NOTE3);
__delay_cycles(SHORT_BEAT * 500);
buzzerOn(PING_AN_NOTE2);
__delay_cycles(SHORT_BEAT * 200);
buzzerOn(PING_AN_NOTE1);
__delay_cycles(SHORT_BEAT * 300);
buzzerOn(PING_AN_NOTE1);
__delay_cycles(LONG_BEAT * 5000);
}
}
void main() {
WDTCTL = WDTPW + WDTHOLD; // 停用看门狗
P3DIR |= BUZZER_PIN; // 将蜂鸣器引脚设为输出
playPingAnSong(); // 播放祝你平安歌曲
}
```
这段代码中,使用时长函数来控制播放歌曲中的不同音符的时长,蜂鸣器控制函数则播放具体的音符,并且等待指定时长之后再停止发声。使用while (1) 循环让歌曲可以无限循环播放,直到设备被关闭。
阅读全文