新聞中心

EEPW首頁 > 嵌入式系統(tǒng) > 設(shè)計應(yīng)用 > 基于Atmega16L的簡單音樂制作

基于Atmega16L的簡單音樂制作

作者: 時間:2012-10-08 來源:網(wǎng)絡(luò) 收藏

一直想要搞下AVR,因為是電氣而不是電子專業(yè)的,整天對著電機(jī)啊,交流調(diào)速啊,復(fù)雜的計算公式,所以學(xué)習(xí)電子類的東西比較麻煩,最近才有大塊的時間來學(xué)習(xí)AVR,馬潮的《AVR單片機(jī)嵌入式系統(tǒng)原理與應(yīng)用實踐》不錯。

想想也算搞過一些程序了,空間里也沒有貼過AVR的程序,就算來個突破下

做了一小段的《卡農(nóng)》高潮部分。聽著感覺不錯,呵呵,以前用51的匯編寫過《歡樂女神》,聽上去不跑調(diào),但是用C51來做,誤差實在是太大了,根本沒辦法聽,這次用mega16,外掛8M的晶振,做的是一小段的《卡農(nóng)》,因為高音的頻率太高,蜂鳴器完全受不了,直接破音(哎,什么叫能力有限),所以都降低了7度,即高音變成中音,中音變成低音。聽上去還可以,但是難免有些音會走不準(zhǔn)。

不廢話貼下程序(注解為英文,希望不會寫錯,編譯器:(WINAVR),仿真器:AVR stutio;熔絲位cksel0~cksel3 :“1111”)

//--------------------------------
// by Witnessiz
// chip :
// 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;
}
}
}




關(guān)鍵詞: Atmega16L 音樂制作 GCC

評論


相關(guān)推薦

技術(shù)專區(qū)

關(guān)閉