- 蜂鸣器没有特定的引脚,随便定义一个就OK。
- 单片机的内部RAM容量比较小,所以常数数组一般放在程序存储区处,以减少RAM数据区的使用。
- 音律和谱曲数组是copy大佬的。
- 用的T0中断请求
#include
#define uchar unsigned char
sbit beepIO=P1^5;
uchar m,n;
uchar code T[49][2]= {{0,0},
{0xF9,0x1F},{0xF9,0x82},{0xF9,0xDF},{0xFA,0x37},{0xFA,0x8A},{0xFA,0xD8},{0xFB,0x23},{0xFB,0x68},{0xFB,0xAA},{0xFB,0xE9},{0xFC,0x24},{0xFC,0x5B},
{0xFC,0x8F},{0xFC,0xC1},{0xFC,0xEF},{0xFD,0x1B},{0xFD,0x45},{0xFD,0x6C},{0xFD,0x91},{0xFD,0xB4},{0xFD,0xD5},{0xFD,0xF4},{0xFE,0x12},{0xFE,0x2D},
{0xFE,0x48},{0xFE,0x60},{0xFE,0x78},{0xFE,0x86},{0xFE,0xA3},{0xFE,0xB6},{0xFE,0xC9},{0xFE,0xDA},{0xFF,0xEB},{0xFE,0xFA},{0xFF,0x09},{0xFF,0x17},
{0xFF,0x24},{0xFF,0x30},{0xFF,0x3C},{0xFF,0x47},{0xFF,0x51},{0xFF,0x5B},{0xFF,0x64},{0xFF,0x6D},{0xFF,0x75},{0xFF,0x7D},{0xFF,0x84},{0xFF,0x8B}
};
uchar code music[][2]= {{0,4},
{0,1},{1,1},{3,1},{5,1},{6,1},{8,1},{10,1},{12,1},{13,1},
{0,1},{13,1},{15,1},{17,1},{18,1},{20,1},{22,1},{24,1},{25,1},
{0,1},{25,1},{27,1},{29,1},{30,1},{32,1},{34,1},{36,1},{37,1},
{0,1},{37,1},{39,1},{41,1},{42,1},{44,1},{46,1},{48,2},
{0,4},{24,4},{24,4},{21,4},{19,4},{21,4},{14,8},{19,4},{21,4},{24,4},{21,4},{19,16},
{0,4},{24,4},{24,4},{21,4},{19,4},{21,4},{12,8},{19,4},{21,4},{24,4},{19,4},{17,16},
{0,4},{17,4},{19,4},{21,4},{24,4},{26,4},{24,4},{22,4},{24,4},{21,4},{21,4},{19,4},{19,16},
{0,4},{17,4},{19,4},{17,4},{17,4},{19,4},{17,4},{19,4},{19,4},{21,8},{24,4},{21,4},{21,12},
{0,4},{24,4},{24,4},{21,4},{19,4},{21,4},{14,8},{19,4},{21,4},{24,4},{21,4},{19,16},
{0,4},{24,4},{24,4},{21,4},{19,4},{21,4},{12,8},{19,4},{21,4},{24,4},{19,4},{17,16},
{0,4},{17,4},{19,4},{21,4},{24,4},{26,4},{24,4},{22,4},{24,4},{21,4},{21,4},{19,4},{19,12},
{12,4},{21,8},{19,8},{19,4},{17,20},
{0xFF,0xFF}
};
void delay(uchar p)
{
uchar i,j;
for(; p>0; p--)
for(i=181; i>0; i--)
for(j=181; j>0; j--);
}
void T0_int() interrupt 1
{
beepIO=!beepIO;
TH0=T[m][0];
TL0=T[m][1];
}
void main()
{
uchar i=0;
TMOD=0x01;
EA=1;
ET0=1;
while(1)
{
m=music[i][0];
n=music[i][1];
if(m==0x00)
{
TR0=0;
delay(n);
i++;
}
else if(m==0xFF)
{
TR0=0;
delay(30);
i=0;
}
else if(m==music[i+1][0])
{
TR0=1;
delay(n);
TR0=0;
i++;
}
else
{
TR0=1;
delay(n);
i++;
}
}
}