基于51单片机设置数码管上限,下限和当前值并超出范围蜂鸣器报警的keil程序
时间: 2024-02-23 10:58:47 浏览: 27
以下是一个基于51单片机的Keil C语言程序,可以设置数码管的上限、下限和当前值,同时当当前值超出范围时,蜂鸣器会发出报警声。
```c
#include <reg51.h>
sbit beep=P1^5; //定义蜂鸣器控制端口
sbit DIO=P1^6; //定义数码管数据线
sbit CLK=P1^7; //定义数码管时钟线
void delay(unsigned int xms) //延时函数
{
unsigned int i,j;
for(i=xms;i>0;i--)
for(j=112;j>0;j--);
}
void writeByte(unsigned char dat) //写入字节
{
unsigned char i;
for(i=0;i<8;i++)
{
DIO=dat&0x01;
CLK=0;
dat>>=1;
CLK=1;
}
}
void writeCMD(unsigned char cmd) //写入命令
{
CLK=0;
writeByte(0x08); //选择控制字模式
writeByte(cmd); //写入命令字
CLK=1;
}
void writeDAT(unsigned char dat) //写入数据
{
CLK=0;
writeByte(0x0c); //选择数据字模式
writeByte(dat); //写入数据
CLK=1;
}
void init() //数码管初始化
{
writeCMD(0x01); //清除显示
writeCMD(0x06); //设定输入方式
writeCMD(0x0c); //打开显示
writeCMD(0x38); //选择8位数据接口
}
void display(unsigned char num) //数码管显示函数
{
if(num>=0 && num<=99) //数字在设置范围内
{
unsigned char ten=num/10;
unsigned char unit=num%10;
writeDAT(ten+'0'); //显示十位
writeDAT(unit+'0'); //显示个位
}
else //数字超出设置范围
{
beep=1; //蜂鸣器报警
delay(100);
beep=0;
delay(100);
}
}
void main()
{
unsigned char upper=90; //设置上限值为90
unsigned char lower=10; //设置下限值为10
unsigned char current=50; //设置当前值为50
init(); //数码管初始化
while(1)
{
display(current); //数码管显示当前值
if(P1^0==0) //按键S1按下
{
current++; //当前值加1
if(current>upper) //当前值超出上限
current=upper; //将当前值设为上限
}
if(P1^1==0) //按键S2按下
{
current--; //当前值减1
if(current<lower) //当前值低于下限
current=lower; //将当前值设为下限
}
delay(10); //延时10ms
}
}
```
在程序中,我们首先定义了数码管、蜂鸣器和按键的控制端口,然后编写了写入字节、写入命令和写入数据的函数。接着编写了数码管初始化函数和数码管显示函数,最后在主函数中实现了数码管的设置和显示,同时监测按键的状态,根据按键状态修改当前值,并判断当前值是否超出设置范围,如果超出范围则发出蜂鸣器报警。