
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
3.15 K1~K4控制数码管加减演示
上一个案例所显示的最大数字为8,本例重新编写程序,在数码管上显示000~255范围内的任意整数,而且,在不松开按键时,数字会按一定时间间隔持续递增或递减。
程序设计调试与实训:
本例要点在于函数Show_Counts_ON_DSY的编写,000~255之间的整数要显示在3位数码管上时,需要先将待显示的3位整数分解为3个数位,然后根据它们的值提取对应段码。
本例固定显示3个数位,读者可修改程序,不显示高位无效的0,如002仅显示2,039仅显示39。
源程序代码:
//----------------------------------------------------------------- // 名称: K1~K4 控制数码管加减演示 //----------------------------------------------------------------- // 说明: K1按下后加1计数, // K2按下后减1计数, // K3按下后清零。 //----------------------------------------------------------------- #include <reg51.h> #include <intrins.h> #define uchar unsigned char #define uint unsigned int //0~9的数码管段码,最后一个为关闭 uchar code DSY_CODE[] = {0xC0,0xF9,0xA4,0xB0,0x99,0x92,0x82,0xF8,0x80,0x90,0xff}; //待显示的3位数 uchar Num_Buffer[] = {0,0,0}; //按键代码,按键计数 uchar Key_Code,Key_Counts=0; //----------------------------------------------------------------- // 延时 //----------------------------------------------------------------- void DelayMS(uint x) { uchar t; while(x--) for(t = 0; t < 120; t++); } //----------------------------------------------------------------- // 显示子程序 //----------------------------------------------------------------- void Show_Counts_ON_DSY() { uchar i,j = 0x01; Num_Buffer[2] = Key_Counts / 100; Num_Buffer[1] = Key_Counts / 10 % 10; Num_Buffer[0] = Key_Counts % 10; for (i = 0;i < 3; i++) { j = _cror_(j,1); P2 = j; P0 = DSY_CODE[Num_Buffer[i]] ; DelayMS(1); } } //----------------------------------------------------------------- // 主程序 //----------------------------------------------------------------- void main() { uchar i; P0 = 0xFF; P1 = 0xFF; P2 = 0x00; Key_Code = 0xFF; while(1) { Show_Counts_ON_DSY(); P1 = 0xFF; Key_Code = P1; //有键按下时,数码管刷新显示30次,该行代码同时起到了延时作用 if (Key_Code != 0xFF) for(i = 0; i < 30; i++) Show_Counts_ON_DSY(); switch(Key_Code) { case 0xFE: if (Key_Counts < 255) Key_Counts++; break; case 0xFD: if (Key_Counts > 0) Key_Counts--; break; case 0xFB: Key_Counts = 0; } Key_Code = 0xFF; } }