修改自51单片机,launchpad的P10连接蜂鸣器,蜂鸣器演奏《八月桂花》
1 #include "msp430g2553.h" 2 3 unsigned char n=0; //n为节拍常数变量 4 unsigned char music_tab[] ={ 5 0x18, 0x30, 0x1C , 0x10, //格式为: 频率常数, 节拍常数, 频率常数, 节拍常数, 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) //控制频率延时 57 { 58 unsigned i=3*m; 59 while(--i); 60 } 61 62 void delaymms(unsigned int a) //毫秒延时子程序 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为频率常数变量 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 } //如果碰到结束符,延时1秒,回到开始再来一遍 94 else if(p==0xff) 95 { 96 i=i+1; 97 delaymms(100); 98 TACTL &=~MC_1; 99 continue; 100 } //若碰到休止符,延时100ms,继续取下一音符 101 else 102 { 103 m=music_tab[i++]; 104 n=music_tab[i++]; 105 } //取频率常数 和 节拍常数 106 107 TACTL |= MC_1+TACLR; //开定时器 108 while(n!=0) P1OUT ^= BIT0,delay(m); //等待节拍完成 109 TACTL &=~MC_1; //关定时器 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 }