MSP430G2 LaunchPad, how to play music with buzzer
[Copy link]
This post was last edited by Jacktang on 2020-5-11 21:56
#include "msp430g2553.h"
unsigned char n=0; //n is the beat constant variable
unsigned char music_tab[] ={
0x18, 0x30, 0x1C , 0x10, //Format: frequency constant, beat constant, frequency constant, beat constant,
0x20, 0x40, 0x1C , 0x10,
0x18, 0x10, 0x20 , 0x10, 0x1C
, 0x10, 0x18 , 0x40, 0x1C,
0x20, 0x20 , 0x20, 0x1C
, 0x20, 0x18 , 0x20, 0x20
, 0x80, 0xFF , 0x20,
0x30, 0x1C, 0x10 , 0x18,
0x20, 0x15, 0x20 , 0x1C,
0x20, 0x20, 0x20 , 0x26,
0x40, 0x20, 0x20 , 0x2B, 0x20
, 0x26, 0x20 , 0x20, 0x20,
0x30, 0x80 , 0xFF,
0x20, 0x20, 0x1C , 0x10, 0x18
, 0x10, 0x20 , 0x20,
0x26, 0x20, 0x2B , 0x20,
0x30, 0x20, 0x2B , 0x40,
0x20, 0x20, 0x1C, 0x10,
0x18, 0x10, 0x20, 0x20
, 0x26, 0x20, 0x2B, 0x20, 0x30, 0x20, 0x2B
, 0x40,
0x20, 0x30, 0x1C, 0x10,
0x18, 0x2 0, 0x15 , 0x20
, 0x1C, 0x20, 0x20 , 0x20,
0x26, 0x40, 0x20 , 0x20, 0x2B,
0x20, 0x26 , 0x20
, 0x20, 0x20, 0x30 , 0x80,
0x20, 0x30, 0x1C , 0x10
, 0x20, 0x10, 0x1C , 0x10,
0x20, 0x20, 0x26 , 0x20, 0x2B, 0x20,
0x30 , 0x20,
0x2B, 0x40, 0x20 , 0x15,
0x1 F, 0x05, 0x20 , 0x10,
0x1C, 0x10, 0x20 , 0x20,
0x26, 0x20, 0x2B , 0x20, 0x30,
0x20, 0x2B , 0x40,
0x20, 0x30, 0x1C , 0x10,
0x18, 0x20, 0x15, 0x20,
0x1C, 0x20, 0x20, 0x20,
0x26, 0x40, 0x20, 0x20, 0x2B,
0x20, 0x26, 0x20,
0x20, 0x20, 0x30, 0x3 0,
0x20, 0x30, 0x1C , 0x10,
0x18, 0x40, 0x1C , 0x20,
0x20, 0x20, 0x26 , 0x40, 0x13
, 0x60, 0x18 , 0x20,
0x15, 0x40, 0x13 , 0x40,
0x18, 0x80, 0x00
};
void delay (unsigned char m) //control frequency delay
{
unsigned i=3*m;
while(--i);
}
void delaymms(unsigned int a) //millisecond delay subroutine
{
unsigned int t;
while(--a)
for(t=0;t<200;t++);
}
void main(void)
{
unsigned char p,m; //m is the frequency constant variableunsigned
char i=0;
WDTCTL = WDTPW + WDTHOLD; // Stop watchdog
P1DIR = 0Xff;
P2DIR = 0Xff;
CCTL0 |= CCIE; // CCR0 interrupt enabled
CCR0 = 10000; //10ms
TACTL = TASSEL_2 ; // SMCLK, contmode
_EINT();
while(1)
{
p=music_tab;
if(p==0x00)
{
i=0;
delaymms(1000);
continue;;
} //If you encounter the end symbol, delay for 1 second and go back to the beginning and start again
else if(p==0xff)
{
i=i+1;
delaymms(100);
TACTL &=~MC_1;
continue;
} //If you encounter a rest symbol, delay for 100ms and continue to take the next note
else
{
m=music_tab[i++];
n=music_tab[i++];
} //Get the frequency constant and beat constant
TACTL |= MC_1+TACLR; //Start the timer
while(n!=0) P1OUT ^= BIT0,delay(m); //Wait for the beat to complete
TACTL &=~MC_1; //Turn off the timer
}
}
// Timer A0 interrupt service routine
#pragma vector=TIMER0_A0_VECTOR
__interrupt void Timer_A (void)
{
n--;
}
|