51单片机用矩阵按键控制无源蜂鸣器发Do Re Mi Fa So La Si Do,用定时器实现代码
时间: 2024-01-24 09:19:16 浏览: 85
以下是51单片机使用矩阵按键控制无源蜂鸣器发Do Re Mi Fa So La Si Do的示例代码,使用定时器实现:
```c
#include <reg52.h>
#define uchar unsigned char
#define uint unsigned int
uchar code DO = 0x3f;
uchar code RE = 0x5f;
uchar code MI = 0x6f;
uchar code FA = 0x77;
uchar code SO = 0x7b;
uchar code LA = 0x7d;
uchar code SI = 0x7e;
uchar code Keytable[] = {0xee, 0xde, 0xbe, 0x7e, 0xed, 0xdd, 0xbd, 0x7d, 0xeb, 0xdb, 0xbb, 0x7b, 0xe7, 0xd7, 0xb7, 0x77};
uchar code Tone[] = {DO, RE, MI, FA, SO, LA, SI, DO};
uchar music = 0xff;
uchar keyvalue = 0xff;
void delay(uint z)
{
uint x,y;
for(x=z;x>0;x--)
for(y=110;y>0;y--);
}
void keyscan()
{
uchar i;
P1 = 0x0f;
if(P1 != 0x0f)
{
delay(10);
if(P1 != 0x0f)
{
P1 = 0x0f;
keyvalue = P1;
P1 |= 0xf0;
keyvalue |= P1;
for(i=0;i<16;i++)
{
if(keyvalue == Keytable[i])
{
music = i;
break;
}
}
}
}
}
void tm0() interrupt 1
{
TH0 = (65536-5000)/256;
TL0 = (65536-5000)%256;
P2 = Tone[music];
}
void main()
{
TMOD = 0x01;
TH0 = (65536-5000)/256;
TL0 = (65536-5000)%256;
EA = 1;
ET0 = 1;
TR0 = 1;
while(1)
{
keyscan();
if(music != 0xff)
{
TR0 = 0;
TH0 = (65536-5000)/256;
TL0 = (65536-5000)%256;
TR0 = 1;
}
}
}
```
在此示例代码中,`Keytable`数组存储了矩阵按键的扫描码,`Tone`数组存储了发声的频率。`keyscan()`函数用于扫描矩阵按键,若检测到有按键按下,则根据按下的键值设置`music`变量的值。`tm0()`函数为定时器0的中断服务程序,每次中断时将`Tone[music]`输出到P2口,从而使蜂鸣器发声。主函数中不断调用`keyscan()`函数进行按键扫描,并根据按键设置`music`变量的值。若`music`变量不为0xff,则表示有按键按下,此时停止定时器0的计数,重新设置计数值,然后再次启动计数,从而使蜂鸣器发出对应的音符。
阅读全文