帮我写一段msp430f149播放祝你平安歌的代码
时间: 2023-05-22 08:04:38 浏览: 172
好的,以下是一段播放祝你平安歌的代码
```
#include <msp430f149.h>
#define SOUND_PIN BIT0
void delay(unsigned int cnt) {
while(cnt--)__delay_cycles(1000);
}
void tone(int freq) {
TACCR0 = freq;
TACCR1 = freq / 2; // 50% duty cycle
TACCTL1 |= OUTMOD_7; // reset/set mode
}
void no_tone() {
TACCTL1 &= ~OUTMOD_7;
}
void play_sound(int note, int duration) {
tone(note);
delay(duration);
no_tone();
}
void play() {
int song[] = {
262, 250, 0, 294, 250, 0, 330, 500,
294, 500, 262, 500, 294, 500, 330, 500,
330, 250, 0, 350, 250, 0, 392, 500,
330, 500, 294, 500, 262, 500, 294, 500,
262, 250, 0, 294, 250, 0, 330, 500,
294, 500, 262, 500, 294, 500, 330, 500,
294, 250, 0, 330, 250, 0, 350, 500,
392, 250, 0, 0, 250, 0, 392, 500
};
int duration[] = {
4, 4, 2, 4, 4, 2, 2, 2,
4, 4, 4, 4, 4, 4, 2, 2,
4, 4, 2, 4, 4, 2, 2, 2,
4, 4, 4, 4, 4, 4, 2, 2,
4, 4, 2, 4, 4, 2, 2, 2,
4, 4, 4, 4, 4, 4, 2, 2,
4, 4, 2, 4, 4, 2, 2, 2,
4, 4, 4, 4, 4, 4, 2, 2
};
int i;
for(i = 0; i < sizeof(song)/sizeof(song[0]); ++i) {
if(song[i] == 0) {
delay(duration[i]);
} else {
play_sound(song[i], duration[i]);
}
delay(duration[i] / 2);
}
}
void main(void) {
WDTCTL = WDTPW + WDTHOLD; // Stop WDT
P1DIR |= SOUND_PIN; // Make P1.0 an output
TACTL = TASSEL_2 + MC_1 + ID_0; // Timer A2 setup
TACCTL1 = OUTMOD_0 + CCIE;
while(1) {
play();
delay(2000);
}
}
```
该代码通过 MSP430F149 微控制器实现了祝你平安歌的播放。您需要将蜂鸣器连接到微控制器的 P1.0 引脚,然后将代码下载到微控制器中即可播放。
阅读全文