#include<iom16v.h>
#include<macros.h>
void delay_ms(unsigned int n)
{
unsigned int j=0;
while(j<n)
{
delay_1ms();
j++;
}
}
void delay_1ms(void)
{
unsigned int j;
for(j=0;j<1000;j++)
j++;
}
#define uchar unsigned char
#define uint unsigned int
flash uint music_data[] [2]=
{
{440,600},{494,200},{523,600},{443,200},{523,400},{494,200},
{440,200},{494,400},{330,400},{494,600},{523,200},{578,600},
{494,200},{578,400},{523,200},{494,200},{440,800},{659,400},
{880,400},{784,400},{880,200},{784,200},{698,400},{659,200},
{578,200},{659,400},{440,400},{ 0,200},{698,400},{578,200},
{659,600},{523,200},{494,200},{330,200},{523,200},{494,200},
{440,800},{659,400},{880,400},{784,400},{880,200},{784,200},
{698,400},{659,200},{578,200},{659,400},{440,400},{ 0,200},
{698,400},{578,200},{659,600},{523,200},{494,200},{330,200},
{523,200},{494,200},{440,800},{ 0, 0},
};
void port_init(void) //端口初始化函数
{
DDRD=0XFF; //D口配置为输出,驱动蜂鸣器——PD5
//DDRB=0XFF; //B口配置为输出,驱动LED——PB5
//PORTB=0X00; //LED初值为灭
DDRA=0XFF;PORTA=0X00;
DDRB=0XFF;PORTB=0XFF;
DDRC=0XFF;PORTC=0X00;
}
void sound(uchar i)
{
uint x;
x=music_data[i][0]; //取音乐的频率数据
if(x!=0)
{
x=500000/x; //1M时钟数据计算
OCR1A=x; //比较值赋值
TCCR1A=0X40; //允许比较反转输出
}
else
{
TCCR1A=0X00; //频率为0,休止符,不发声
}
}
unsigned char j;
unsigned char k;
unsigned char m;
void main(void)
{
uchar i=0;
port_init();
TCCR1A=0X40; //端口初始化
TCCR1B=0X09; //将T/C1配置为比较匹配,OC1A取反
//while(1)
//{
for(k=0;k<1000;k++)
{PORTA=0X01;PORTB=0XFE;PORTC=0XFF;delay_ms(1);
PORTA=0X02;PORTB=0XFD;PORTC=0XFF;delay_ms(1);
PORTA=0X04;PORTB=0XDB;PORTC=0XE3;delay_ms(1);
PORTA=0X08;PORTB=0X80;PORTC=0XFC;delay_ms(1);
PORTA=0X10;PORTB=0X8B;PORTC=0XE1;delay_ms(1);
PORTA=0X20;PORTB=0XDB;PORTC=0XFF;delay_ms(1);
PORTA=0X40;PORTB=0XFD;PORTC=0XFF;delay_ms(1);
PORTA=0X80;PORTB=0XFE;PORTC=0XFF;delay_ms(1);}
for(m=0;m<1000;m++)
{
while(music_data[i][1]!=0) //等待最后一个音符到来
{
sound(i); //输出音符
delay_ms(music_data[i][1]);//节拍延时
TCCR1A=0X00; //奏完一个音符停止
//PORTB^=1<<5aa; //音符节拍由LD5闪亮显示
PORTD|=1<<5; //PD5
i++; //准备下一个音符
}
delay_ms(1000);
i=0; //一遍结束,停1秒,从头开始
delay_ms(100);
}
}
一周热门 更多>