原理,要根据乐谱不同的定时器初值装入,定时时间到,扬声器管脚翻转,我有一程序,你只需将乐谱按规定转化为MUSIC[]代码即可
//主程序查音符码,将不同的初值装入定时器,定时器每中断一次,P3.7取反一次,形成不同频率的方波
//11代表低音哆 21代表高音哆 1代表中音哆
#include<reg52.h>
sbit SPK = P3^7; //P3.7外接扬声器
sbit dula=P2^6;这是数码管显示用的,显示程序同中时顺便也是延时程序
sbit wela=P2^7;
#define uint unsigned int;
#define uchar unsigned char;
unsigned char x,y;
uchar bai_c,shi_c,ge_c;
uchar a,b,c;
uchar i1,i2,i3;
uchar code MUSIC[]={ 0,0,0,0,16,16,1,1, 15,15,16,16,1,1,1,1, 5,5,6,6,4,4,3,3, 2,2,2,2,2,2,5,5, 5,5,2,2,4,4,3,3, 2,2,1,2,4,4,4,4,
16,16,1,1,2,2,4,4, 2,1,16,1,15,15,15,15, 16,16,16,16,15,15,15,15, 15,15,15,15,15,15,15,15, 0,0,5,5,5,5,0,0, 5,5,5,5,4,4,4,4,
5,5,5,5,2,2,2,2, 2,2,5,5,4,4 ,4,4, 16,16,1,1,2,2,2,2, 4,4,2,2,2,2,4,4, 5,5,5,5,5,5,6,6, 21,21,21,21,6,6,21,21,
21,21,6,6,5,5,5,5, 5,5,6,6,5,5,4,4, 2,2,2,2,2,2,5,5, 5,5,2,2,4,4,3,3, 2,2,1,2,4,4,4,4, 16,16,1,1,2,2,4,4,
2,1,16,1,15,15,15,15, 16,16,16,16,15,15,15,15, 5,5,6,6,5,5,6,6, 5,5,4,4,5,5,5,5};
uchar code table[] = { 0,0xfc,0xfc,0xfd,0xfd,0xfd,0xfd,0xfe,0,0,0, //0-10定时半周期的初始值中音123 4 5 67高8位,8,9,10为补位码
0xf8,0xf9,0xfa,0xfa,0xfb,0xfb,0xfc,0,0,0, //低音1 2 3 4 5 67高8位
0xfe,0xfe,0xfe,0xfe,0xfe,0xfe,0xff, //高音1 2 3 4 5 67高8位
0,0x44,0xad,0x0a,0x34,0x82,0xc8,0x06,0,0,0, //中音123 4 5 67低8位
0x89,0x59,0x13,0x68,0x04,0x90,0x0c,0 ,0,0, //低音1 2 3 4 5 6 7低8位
0x22,0x56,0x85,0x9a,0xc1,0xe4,0x03}; //高音1 2 3 4 5 6 7低8位
uchar code table1[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d, //数码管显示数字码
0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71,0x00};
uint i,j,k;
void delay(i) //晶振12MHZ时延时1ms
{
for(j=i;j>0;j--)
for(k=121;k>0;k--);
}
void display(bai_c,shi_c,ge_c)//3位显示程序
{
P0=table1[bai_c]; //显示百位
dula=1;
dula=0;
P0=0xf7;
wela=1;
wela=0;
delay(2);
P0=table1[shi_c]; //显示十位
dula=1;
dula=0;
P0=0xef;
wela=1;
wela=0;
delay(2);
P0=table1[ge_c]; //显示个位
dula=1;
dula=0;
P0=0xdf;
wela=1;
wela=0;
delay(1);
P0=0xff; //显示完毕后关闭最后一位显示
wela=1;
wela=0;
}
void TIM0_ISR() interrupt 1
{
SPK=!SPK;
TH0=table[x]; //载入定时半周期的初始值
TL0=table[x+28];
}
void main(void)
{
TMOD|=0x01;
EA=1;
ET0=1;
while(1)
{
y=0;
while(y<224)
{
i1=y/100;
i2=y/10%10;
i3=y%10;
x=MUSIC[y];
TH0=table[x]; //载入定时半周期的初始值
TL0=table[x+28];
TR0=1; //打开定时器
for(a=25;a>0;a--) //延时125ms
{
display(i1,i2,i3);
}
y++;
TR0=0;
}
}
}
追问用的是汇编语言,