基于Atmega16L的簡(jiǎn)單音樂制作
一直想要搞下AVR,因?yàn)槭请姎舛皇请娮訉I(yè)的,整天對(duì)著電機(jī)啊,交流調(diào)速啊,復(fù)雜的計(jì)算公式,所以學(xué)習(xí)電子類的東西比較麻煩,最近才有大塊的時(shí)間來學(xué)習(xí)AVR,馬潮的《AVR單片機(jī)嵌入式系統(tǒng)原理與應(yīng)用實(shí)踐》不錯(cuò)。
想想也算搞過一些程序了,空間里也沒有貼過AVR的程序,就算來個(gè)突破下
做了一小段的《卡農(nóng)》高潮部分。聽著感覺不錯(cuò),呵呵,以前用51的匯編寫過《歡樂女神》,聽上去不跑調(diào),但是用C51來做,誤差實(shí)在是太大了,根本沒辦法聽,這次用mega16,外掛8M的晶振,做的是一小段的《卡農(nóng)》,因?yàn)楦咭舻念l率太高,蜂鳴器完全受不了,直接破音(哎,什么叫能力有限),所以都降低了7度,即高音變成中音,中音變成低音。聽上去還可以,但是難免有些音會(huì)走不準(zhǔn)。
不廢話貼下程序(注解為英文,希望不會(huì)寫錯(cuò),編譯器:GCC(WINAVR),仿真器:AVR stutio;熔絲位cksel0~cksel3 :“1111”)
//--------------------------------
// by Witnessiz
// chip : Atmega16L
// frequency : 8,000,000Hz
// function : play music
// output : OC1A(PB5) connect buzzer
//--------------------------------
#includeavr/io.h>
#includeavr/interrupt.h>
#define uchar unsigned char
#define uint unsigned int
const uint note[] = {0,1908,1700,1516,1433,1276,1136,1012,956,865,759,716,638,568,506,470};
const uint beat[] = {0,419,470,528,558,627,704,790,837,925,1054,1117,1254,1408,1581,1702};
//const uchar score[] = {4,8,10,4,9,12,10,8,11,4,6,4,8,12,5,4,6,4,7,8,9,4,5,12,8,12}; //《好久不見》一小段
const uchar score[]={12,4,10,2,11,2,12,4,10,2,11,2,10,2,5,2,6,2,7,2,8,2,9,2,10,2,11,2,10,4,8,2,
9,2,10,4,3,2,4,2,5,2,6,2,5,2,4,2,5,2,8,2,7,2,8,2,6,4,8,2,7,2,6,4,5,2,4,
2,5,2,4,2,3,2,4,2,5,2,6,2,7,2,8,2,6,4,8,2,7,2,8,4,7,2,6,2,7,2,8,2,9,2,
8,2,7,2,8,2,6,2,7,2}; //《canon》
volatile uint note_num,beat_num;
int main()
{
// DDRD |= (1 PD5);
DDRD = 0x20;
PORTD = 0x20;
TCCR1A |= (1 COM1A0); // toggle OC1A on compare match [0x40]
TCCR1B |= (1 WGM12); //Clear Timer on Compare match (CTC) mode [0x80]
TIMSK |= (1 OCIE1A); //Output Compare match Intrrupt Enable [0x10]
beat_num = 1;
TCCR1B = 0x09;
sei();
while(1)
{
}
}
SIGNAL(SIG_OUTPUT_COMPARE1A)
{
if(-- beat_num == 0)
{
TCCR1B = 0x08; //TCCR1B |= (1 WGM12); no clock sourse,stop CTC [0x08]
if(note_num 112)
{
OCR1A = note[score[note_num]];
beat_num = beat[score[note_num]];
note_num ++;
beat_num = beat_num * score[note_num];
note_num ++;
TCCR1B = 0x09; //TCCR1B |= (1 WGM12) | (1 CS10); clkio/1(no prescale),start CTC [0x09]
}
else
{
note_num = 0;
beat_num = 1;
TCCR1B = 0x08;
}
}
}
評(píng)論