C51 Proteus仿真实验22:按键发声
说明
按下不同的按键,蜂鸣器会发出不同频率的声音
Proteus仿真
使用到的元器件:
单片机:AT89C51
电容:CAP
极性电容:CAP-ELEC
电阻:RES、RESPACK-8
晶振:CRYSTAL
按键:BUTTON
蜂鸣器:SOUNDER
C51代码
#include <reg51.h>
#define uchar unsigned char
#define uint unsigned int
sbit Beep = P3^7;
sbit K1 = P1^4;
sbit K2 = P1^5;
sbit K3 = P1^6;
sbit K4 = P1^7;
// 延时函数
void DelayMs(uint ms)
{
uchar i;
while(ms--)
{
for(i=0; i<120; i++);
}
}
// 蜂鸣器播放函数
void Play(uchar t)
{
uchar i;
for(i=0; i<100; i++) // 持续时间
{
Beep = ~Beep; // 翻转蜂鸣器状态
DelayMs(t); // 控制频率
}
Beep = 0; // 确保停止发声
}
void main()
{
P1 = 0xff; // 确保按键为上拉输入
Beep = 0; // 关闭蜂鸣器
while(1)
{
//延时消抖,且等按键释放后再继续执行
if(K1 == 0) { DelayMs(10); if(K1 == 0) { Play(1); while(K1 == 0); } }
if(K2 == 0) { DelayMs(10); if(K2 == 0) { Play(2); while(K2 == 0); } }
if(K3 == 0) { DelayMs(10); if(K3 == 0) { Play(3); while(K3 == 0); } }
if(K4 == 0) { DelayMs(10); if(K4 == 0) { Play(4); while(K4 == 0); } }
}
}