自己用蜂鸣器做的小星星,有用的小伙伴拿去看看吧
#include <reg52.h>
#define uchar unsigned char
sbit beep=P2^0;
uchar m,n; //定义4个八度每八度12分音律共48个音律
uchar code T[49][2]={{0,0},{0xF8,0x8B}, //定义音律为49个二维数组
{0xF8,0xF2},{0xF9,0x5B},
{0xF9,0xB7},{0xFA,0x14},
{0xFA,0x66},{0xFA,0xB9},
{0xFB,0x03},{0xFB,0x4A},
{0xFB,0x8F},{0xFB,0xCF},
{0xFC,0x0B},{0xFC,0x43},
{0xFC,0x78},{0xFC,0xAB},
{0xFC,0xDB},{0xFD,0x08},
{0xFD,0x33},{0xFD,0x5B},
{0xFD,0x81},{0xFD,0xA5},
{0xFD,0xC7},{0xFD,0xE7},
{0xFE,0x05},{0xFE,0x21},
{0xFE,0x3C},{0xFE,0x55},
{0xFE,0x6D},{0xFE,0x84},
{0xFE,0x99},{0xFE,0xAD},
{0xFE,0xC0},{0xFE,0x02},
{0xFE,0xE3},{0xFE,0xF3},
{0xFF,0x02},{0xFF,0x10},
{0xFF,0x1D},{0xFF,0x2A},
{0xFF,0x36},{0xFF,0x42},
{0xFF,0x4C},{0xFF,0x56},
{0xFF,0x60},{0xFF,0x69},
{0xFF,0x71},{0xFF,0x79},
{0xFF,0x81}};
uchar code music[][2]={{0,4},{13,8}, //定义曲谱数组,前数为音律,后数为音符节拍
{13,8},{20,8},
{20,8},{22,8},
{20,8},{20,16},
{18,8},{18,8},
{17,8},{17,8},
{15,8},{15,8},
{13,16},{20,8},
{20,8},{18,8},
{18,8},{17,8},
{17,8},{15,16},
{20,8},{20,8},
{18,8},{18,8},
{17,8},{17,8},
{15,16},{13,8},
{13,8},{20,8},
{20,8},{22,8},
{20,8},{20,16},
{18,8},{18,8},
{17,8},{17,8},
{15,8},{15,8},
{13,16},{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--); //181*181个机器周期约25ms,即1/16个节拍
}
void pause()
{
uchar i,j;
for(i=200;i>0;i--)
for(j=200;j>0;j--);
}
void T0_int() interrupt 1
{
beep=!beep;
TH0=T[m][0];
TL0=T[m][1]; //音律延时周期次数码表赋给定时寄存器作为计数初始值,每TH0TL0个机器周期触发蜂鸣器端口翻转,演奏出不同音符
}
void main()
{
uchar i=0;
TMOD=0x01; //定时器T0
EA=1;
ET0=1;
while(1)
{
m=music[i][0];
n=music[i][1]; //将音律号赋值给m, 将节拍号赋值给n
if(m==0x00) //如果音律号为0
{
TR0=0;
delay(n);
i++; //关闭定时器,延迟n拍,将循环数I加1 ,准备读下一个音符
}
else if(m==0xFF) //如果音律号为1
{
TR0=0;
delay(30);
i=0; //开启节拍延时30个1/16节拍,歌曲停顿2秒,将循环数I置0
}
else if(m==music[i+1][0]) // 否则如果把下一个音律号数给变量m
{
TR0=1;
delay(n);
TR0=0;
pause();
i++; //定时器0打开延迟n拍,关闭定时器T0,读下一个音符,循环数加1读下一个音律
}
else //音符若不为零
{
TR0=1;
delay(n);
i++; //打开定时器,延时n个1/16拍,循环数I加1 ,准备演奏下一个音符
}
}
}
|