修改自51單片機(jī),launchpad的P10連接蜂鳴器,蜂鳴器演奏《八月桂花》
1 #include "msp430g2553.h"
2
3 unsigned char n=0; //n為節(jié)拍常數(shù)變量
4 unsigned char music_tab[] ={
5 0x18, 0x30, 0x1C , 0x10, //格式為: 頻率常數(shù), 節(jié)拍常數(shù), 頻率常數(shù), 節(jié)拍常數(shù),
6 0x20, 0x40, 0x1C , 0x10,
7 0x18, 0x10, 0x20 , 0x10,
8 0x1C, 0x10, 0x18 , 0x40,
9 0x1C, 0x20, 0x20 , 0x20,
10 0x1C, 0x20, 0x18 , 0x20,
11 0x20, 0x80, 0xFF , 0x20,
12 0x30, 0x1C, 0x10 , 0x18,
13 0x20, 0x15, 0x20 , 0x1C,
14 0x20, 0x20, 0x20 , 0x26,
15 0x40, 0x20, 0x20 , 0x2B,
16 0x20, 0x26, 0x20 , 0x20,
17 0x20, 0x30, 0x80 , 0xFF,
18 0x20, 0x20, 0x1C , 0x10,
19 0x18, 0x10, 0x20 , 0x20,
20 0x26, 0x20, 0x2B , 0x20,
21 0x30, 0x20, 0x2B , 0x40,
22 0x20, 0x20, 0x1C , 0x10,
23 0x18, 0x10, 0x20 , 0x20,
24 0x26, 0x20, 0x2B , 0x20,
25 0x30, 0x20, 0x2B , 0x40,
26 0x20, 0x30, 0x1C , 0x10,
27 0x18, 0x20, 0x15 , 0x20,
28 0x1C, 0x20, 0x20 , 0x20,
29 0x26, 0x40, 0x20 , 0x20,
30 0x2B, 0x20, 0x26 , 0x20,
31 0x20, 0x20, 0x30 , 0x80,
32 0x20, 0x30, 0x1C , 0x10,
33 0x20, 0x10, 0x1C , 0x10,
34 0x20, 0x20, 0x26 , 0x20,
35 0x2B, 0x20, 0x30 , 0x20,
36 0x2B, 0x40, 0x20 , 0x15,
37 0x1F, 0x05, 0x20 , 0x10,
38 0x1C, 0x10, 0x20 , 0x20,
39 0x26, 0x20, 0x2B , 0x20,
40 0x30, 0x20, 0x2B , 0x40,
41 0x20, 0x30, 0x1C , 0x10,
42 0x18, 0x20, 0x15 , 0x20,
43 0x1C, 0x20, 0x20 , 0x20,
44 0x26, 0x40, 0x20 , 0x20,
45 0x2B, 0x20, 0x26 , 0x20,
46 0x20, 0x20, 0x30 , 0x30,
47 0x20, 0x30, 0x1C , 0x10,
48 0x18, 0x40, 0x1C , 0x20,
49 0x20, 0x20, 0x26 , 0x40,
50 0x13, 0x60, 0x18 , 0x20,
51 0x15, 0x40, 0x13 , 0x40,
52 0x18, 0x80, 0x00
53 };
54
55
56 void delay (unsigned char m) //控制頻率延時(shí)
57 {
58 unsigned i=3*m;
59 while(--i);
60 }
61
62 void delaymms(unsigned int a) //毫秒延時(shí)子程序
63 {
64 unsigned int t;
65 while(--a)
66 for(t=0;t<200;t++);
67 }
68
69 void main(void)
70 {
71 unsigned char p,m; //m為頻率常數(shù)變量
72 unsigned char i=0;
73
74 WDTCTL = WDTPW + WDTHOLD; // 停止看門狗
75
76 P1DIR = 0Xff;
77 P2DIR = 0Xff;
78
79 CCTL0 |= CCIE; // CCR0 interrupt enabled
80 CCR0 = 10000; //10ms
81 TACTL = TASSEL_2 ; // SMCLK, contmode
82 _EINT();
83
84
85 while(1)
86 {
87 p=music_tab[i];
88 if(p==0x00)
89 {
90 i=0;
91 delaymms(1000);
92 continue;;
93 } //如果碰到結(jié)束符,延時(shí)1秒,回到開始再來一遍
94 else if(p==0xff)
95 {
96 i=i+1;
97 delaymms(100);
98 TACTL &=~MC_1;
99 continue;
100 } //若碰到休止符,延時(shí)100ms,繼續(xù)取下一音符
101 else
102 {
103 m=music_tab[i++];
104 n=music_tab[i++];
105 } //取頻率常數(shù) 和 節(jié)拍常數(shù)
106
107 TACTL |= MC_1+TACLR; //開定時(shí)器
108 while(n!=0) P1OUT ^= BIT0,delay(m); //等待節(jié)拍完成
109 TACTL &=~MC_1; //關(guān)定時(shí)器
110 }
111
112 }
113
114
115 // Timer A0 interrupt service routine
116 #pragma vector=TIMER0_A0_VECTOR
117 __interrupt void Timer_A (void)
118 {
119 n--;
120 }