数码管显示温度,按按键进入设置界面,按上下键设置参数,C51例程
时间: 2024-03-18 19:42:31 浏览: 20
好的,以下是C51的代码:
```C
#include <reg52.h> // 引入头文件
#define uchar unsigned char
#define uint unsigned int
// 数码管段选值
uchar code Table[]={
0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,
0x80,0x90,0x88,0x83,0xC6,0xA1,0x86,0x8E
};
uchar TMP; // 存储温度值
uchar Key; // 存储按键值
uchar flag; // 按键标志位
void Delayms(uint); // 延时函数
void Display(); // 显示函数
void Set(); // 设置函数
void main()
{
P0=0x00; // 初始化P0口
P2=0xFF; // 初始化P2口
TMP=25; // 默认温度为25度
flag=0; // 按键标志位初始为0
while(1)
{
Display(); // 显示温度
if(flag==1) // 按键标志位为1,进入设置
{
Set();
flag=0; // 设置完后,按键标志位清零
}
}
}
// 延时函数
void Delayms(uint n)
{
uint i,j;
for(i=0;i<n;i++)
for(j=0;j<120;j++);
}
// 显示函数
void Display()
{
uchar shi,ge;
shi=TMP/10; // 十位数
ge=TMP%10; // 个位数
P2=0xFF; // 关闭所有数码管
P0=Table[shi]; // 显示十位数
P2=0xFE; // 打开第一位数码管
Delayms(5); // 延时5ms
P2=0xFF; // 关闭所有数码管
P0=Table[ge]; // 显示个位数
P2=0xFD; // 打开第二位数码管
Delayms(5); // 延时5ms
}
// 设置函数
void Set()
{
while(1)
{
P2=0xFF; // 关闭所有数码管
P0=0x00; // 显示“--”
P2=0xFE; // 打开第一位数码管
Delayms(5); // 延时5ms
P2=0xFF; // 关闭所有数码管
P0=0x00; // 显示“--”
P2=0xFD; // 打开第二位数码管
Delayms(5); // 延时5ms
Key=P2; // 读取按键值
if(Key!=0xFF) // 如果有按键按下
{
Delayms(10); // 延时10ms
Key=P2; // 再次读取按键值
if(Key!=0xFF) // 确认按键按下
{
if(Key==0xFE) // 上键
{
if(TMP<50)
TMP++;
}
else if(Key==0xFD) // 下键
{
if(TMP>0)
TMP--;
}
else if(Key==0xFB) // 确认键
{
break; // 退出设置
}
while(Key!=0xFF); // 等待按键松开
}
}
}
}
```
这个代码实现的功能为:数码管显示温度,按下P2口的按键进入设置界面,按上下键设置温度值,按确认键退出设置界面,最大温度为50度,最小温度为0度。