51单片机状态机键盘检测
2024-08-12 来源:cnblogs
#include #define uint unsigned int #define uchar unsigned char sbit key1=P3^2; typedef enum keystate{initstate,affirmstate,singlestate,repeatstate};// typedef enum±íʾ¶¨ÒåÁËÒ»¸öö¾ÙÐ͵ÄÊý¾Ý½á¹¹ ²»¸³ÖµµÄ»° ĬÈÏ {0 1 2 3} // ³õʼ״̬£¬È·ÈÏ״̬£¬µ¥´Î´¥·¢×´Ì¬£¬Á¬Ðø´¥·¢×´Ì¬ typedef enum ledstate{D0,D1,D2,D3,D4,D5,D6,D7,D8};//Á÷Ë®µÆ8¸ö״̬ 0 1 2 3 4 5 6 7 void time0init()//¶¨Ê±Æ÷T0³õʼ»¯ { TMOD=0X01; //T0·½Ê½1 TH0=(65536-10000)/256;//³õÖµ10ms TL0=(65536-10000)%256; TR0=1; //Æô¶¯¶¨Ê±Æ÷0 EA=1; //¿ª×ÜÖÐ¶Ï ET0=1;//¿ªÆô¶¨Ê±Æ÷0 } /*Ï£Íûº¯ÊýÖеľֲ¿±äÁ¿µÄÖµÔÚº¯Êýµ÷ÓýáÊøºó²»Ïûʧ¶ø±£ÁôÔÖµ, ¼´ÆäÕ¼ÓõĴ洢µ¥Ôª²»ÊÍ·Å,ÔÚÏÂÒ»´Îº¯Êýµ÷ÓÃʱ,¸Ã±äÁ¿ÒÑÓÐÖµ, ¾ÍÊÇÉÏÒ»´Îº¯Êýµ÷ÓýáÊøʱµÄÖµ. ÕâÊǾÍÓ¦¸ÃÖ¸¶¨¸Ã¾Ö²¿±äÁ¿Îª'¾Ö²¿¾²Ì¬±äÁ¿',ÓÃstatic¼ÓÒÔ˵Ã÷*/ uchar keyscan(void) //°´¼üɨÃ躯Êý { staticuchar keystatevalue=0; //°´¼ü״ֵ̬ ¼ÓStaticÑÓ³¤Ê±¼äÖÜÆÚ×÷ÓÃÓò²»±ä staticuchar presstime=0; // uchar key_value; //°´¼ü״ֵ̬ uchar num; key_value=key1; //¶ÁÈ¡°´¼ü״ֵ̬£¨0 1£© switch(keystatevalue) { case initstate: //³õʼ״̬ if(key_value==0) //˵Ã÷°´¼ü°´Ï {keystatevalue=affirmstate;}//¼ÈÈ»°´¼ü°´Ï ¾Í±ä³ÉÈ·ÈÏ״̬ else {keystatevalue=initstate;}//·ñÔò»¹Êdzõʼ״̬ break; case affirmstate://È·ÈÏ״̬ if(key_value==0) { keystatevalue=singlestate; //±äΪµ¥´Î´¥·¢×´Ì¬ } else { keystatevalue=initstate; // ¶¶¶¯Ã»ÓÐÏû³ýÍí£¬½øÈë³õʼ״̬ } break; case singlestate: //µ¥´Î´¥·¢×´Ì¬ presstime++; //Óö¨Ê±Æ÷ ÿ¹ý10ms¼Ó1´Î if(presstime>100) //ʱ¼ä´óÓÚ1S Çл»µ½Á¬·¢×´Ì¬ { presstime=0; keystatevalue=repeatstate; //״̬Çл»µ½Á¬·¢ } else if(key_value==1) //ʱ¼äСÓÚ1S²¢ÇÒÈç¹û°´¼üÊÍ·Å { keystatevalue=initstate; num++; //µÆµÄ±ä»¯ if(num==8) { num=0; } } break; case repeatstate: //Á¬Ðø´¥·¢×´Ì¬ if(key_value==1) //Èç¹û°´¼üÊͷžͽøÈë³õʼ״̬ { keystatevalue=initstate; } presstime++; if(presstime>10)//ÿ¹ý100msÁ¬·¢Ò»´Î { presstime=0; num++; if(num==8) { num=0; } } break; default: keystatevalue=initstate; break; } return num; } void keypress() //°´¼ü´¦Àíº¯Êý { uchar keynum; //ÓÃÓÚ¶ÁÈ¡°´¼üɨÃèµÄ·µ»ØÖµ if(TF0)//TF0=1ÓÐÒç³ö,˵Ã÷10msʱ¼äµ½ { TF0=0; TH0=(65536-10000)/256;//ÖØ×°³õÖµ TL0=(65536-10000)%256;//ÖØ×°³õÖµ keynum=keyscan();//¶ÁÈ¡°´¼üɨÃèµÄ·µ»ØÖµ£¬Ò²¾ÍÊÇ°´¼ü°´ÏÂʱµÄ²Ù×÷Öµ } switch(keynum)//¶Áµ½keynumµÄÖµ ÓÃÓÚÅжÏÄĸöָʾµÆÁÁ { case D0: P0=0XFE;break; case D1: P0=0XFD;break; case D2: P0=0XFB;break; case D3: P0=0XF7;break; case D4: P0=0XEF;break; case D5: P0=0XDF;break; case D6: P0=0XBF;break; case D7: P0=0X7F;break; default: P0=0XFF;break; } } void main(void) { time0init(); while(1) { keypress(); } }
上一篇:keil应用的中的问题