用数码管的后三位显示一个十进制数,变化范围为000~255,
开始时显示为255,
每按下S2键一次,数值加5;
每按下S3键一次,数值减5;
每按下S4键一次,数值回到255;
按下S5键一次,利用定时器T1功能使数值开始自动每秒加5,再次按下S5键,数值停止自动加5,并回到255。
#include<reg52.h> #define uchar unsigned char #define uint unsigned int sbit key1=P3^4; sbit key2=P3^5; sbit key3=P3^6; sbit key4=P3^7; sbit dula=P2^6; sbit wela=P2^7; uchar code table[]={ 0x3f,0x06,0x5b,0x4f, 0x66,0x6d,0x7d,0x07, 0x7f,0x6f,0x77,0x7c, 0x39,0x5e,0x79,0x71 }; void delayms(uint); uchar numt0,num,n; void display(uchar numdis){ uchar bai,shi,ge; bai=numdis/100; shi=numdis%100/10; ge=numdis%10; P0=0x00; dula=1; P0=table[bai]; dula=0; P0=0xff; wela=1; P0=0xdf; //位选数据 wela=0; delayms(5); P0=0x00; dula=1; P0=table[shi]; dula=0; P0=0xff; wela=1; P0=0xbf; wela=0; delayms(5); P0=0x00; dula=1; P0=table[ge]; dula=0; P0=0xff; wela=1; P0=0x7f; wela=0; delayms(5); } void delayms(uint xms){ uint i,j; for(i=xms;i>0;i--){ for(j=110;j>0;j--); } } void init(){ TMOD=0x11; //设置定时器1为工作方式1(0000 0001) TH1=(65536-45872)/256; TL1=(65536-45872)%256; EA=1; //开总中断 ET1=1; //开启定时器0中断 num=255; } void keyscan(){ if(key1==0){ delayms(10); if(key1==0){ num=num+5; if(num==256){ num=0; } while(!key1); //等待释放按键 } } if(key2==0){ delayms(10); if(key2==0){ if(num==0){ num=255; } num=num-5; while(!key2); //等待释放按键 } } if(key3==0){ delayms(10); if(key3==0){ num=255; while(!key3); //等待释放按键 } } if(key4==0){ delayms(10); if(key4==0){ while(!key4); //等待释放按键 if(TR1){ num=255; } TR1=~TR1; } } } void main(){ init(); while(1){ keyscan(); display(num); } } void T0_time() interrupt 3{ TH1=(65536-45872)/256; TL1=(65536-45872)%256; numt0++; if(numt0==20){ numt0=0; num=num+5; if(num==256){ num=0; } } }
独立按键实验演示_哔哩哔哩_bilibili