微波EDA网,见证研发工程师的成长!
首页 > 硬件设计 > 嵌入式设计 > 基于Atmega16L的简单音乐制作

基于Atmega16L的简单音乐制作

时间:10-08 来源:互联网 点击:

一直想要搞下AVR,因为是电气而不是电子专业的,整天对着电机啊,交流调速啊,复杂的计算公式,所以学习电子类的东西比较麻烦,最近才有大块的时间来学习AVR,马潮的《AVR单片机嵌入式系统原理与应用实践》不错。

想想也算搞过一些程序了,空间里也没有贴过AVR的程序,就算来个突破下

做了一小段的《卡农》高潮部分。听着感觉不错,呵呵,以前用51的汇编写过《欢乐女神》,听上去不跑调,但是用C51来做,误差实在是太大了,根本没办法听,这次用mega16,外挂8M的晶振,做的是一小段的《卡农》,因为高音的频率太高,蜂鸣器完全受不了,直接破音(哎,什么叫能力有限),所以都降低了7度,即高音变成中音,中音变成低音。听上去还可以,但是难免有些音会走不准。

不废话贴下程序(注解为英文,希望不会写错,编译器: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;
}
}
}


Copyright © 2017-2020 微波EDA网 版权所有

网站地图

Top