实现功能:数码管可以显示0-99两位数字,用三个按键分别表示加、减、复位。
按一下加按键,数字加1;按一下减按键,数字减1。初始化显示为学号后两位。
Proteus仿真电路图如下:
单片机源程序如下:
- #include<reg51.h>
- #define uchar unsigned char
- #define uint unsigned int
- uchar code seg[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};//共阳极数码管编码
- sbit up=P2^2; //加1按键
- sbit down=P2^3; //减1按键
- sbit clear=P2^4; //初始化按键,学号后两位08
- sbit shiwei=P2^0; //数码管十位位选
- sbit gewei=P2^1; //数码管个位位选
- char ge=0; //定义个位初始值
- char shi=0; //定义十位初始值
- char shuzi=8; //定义初始化值
- void delay(uint);//延时函数
- void display();//数码管显示函数
- void main()
- {
- while(1)
- {
- if(up==0)//加1按键按下检测
- {
- delay(10);//消抖
- if(up==0)
- {
- shuzi++;
- if(shuzi==100)//加到99变回0
- shuzi=0;
- }
- while(up==0)//松手检测出后显示数字
- {
- display();
- }
- }
-
- if(down==0)//减1按键按下检测
- {
- delay(10);//消抖
- if(down==0)
- {
- shuzi--;
- if(shuzi==(-1))//减到0变回99
- {
- shuzi=99;
- }
- }
- while(down==0)//松手检测出后显示数字
- {
- display();
- }
- }
- if(clear==0)//初始化(08)按键按下检测
- {
- delay(10);//消抖
- if(clear==0)
- {
- shuzi=8;//初始化显示学号后两位08
- }
- while(clear==0)//松手检测出后显示数字
- {
- display();
- }
- }
- display();
- }
- }
- void delay(uint ms)//延时函数
- {
- uint i,j;
- for(i=ms;i>0;i--)
- for(j=120;j>0;j--);
- }
- void display() //数码管显示函数声明
- {
- ge=shuzi%10; //计算个位处数码管的数值
- shi=shuzi/10; //计算十位处数码管的数值
- gewei=1; //关闭数码管输入,防止数据有误
- shiwei=1; //关闭数码管输入,防止数据有误
- P0=seg[ge]; //送入段选值
- gewei=0; //导通数码管个位位选
- delay(2);
- gewei=1; //关闭个位位选
- P0=seg[shi]; //送入段选值
- shiwei=0; //导通数码管十位位选
- delay(2);
- shiwei=1; //关闭十位位选
- }
复制代码
所有资料51hei提供下载:
数码显示.zip
(100.93 KB, 下载次数: 54)
|