按鍵消抖這樣寫,不要用delay
- #include "reg51.h"
- #include "intrins.h"
- #define u8 unsigned char
- #define u16 unsigned int
- #define u32 unsigned long
- #define KEY_TIME 10 //按鍵消抖時間毫秒
- //定時器0 16位 12T時鐘 1毫秒 根據晶振頻率計算TH0與TL0初值:
- #define TH_1ms 0xFC
- #define TL_1ms 0x18
- sbit sKey1 = P1 ^ 0;
- sbit sKey2 = P1 ^ 1;
- sbit sKey3 = P1 ^ 2;
- u8 bdata b8;
- sbit Key1 = b8 ^ 0;
- sbit Key2 = b8 ^ 1;
- sbit Key3 = b8 ^ 2;
- void InitTimer0(void){
- TMOD = 0x01;
- TH0 = TH_1ms;
- TL0 = TL_1ms;
- EA = 1;
- ET0 = 1;
- TR0 = 1;
- }
- u8 led = 1;
- u8 flag;
- void main(){
- InitTimer0();
- while (1) {
- if (!Key1) {
- flag = 1;
- while (!Key1);
- }
- if (!Key2) {
- flag = 0;
- while (!Key2);
- }
- if (!Key3) {
- flag = 2;
- while (!Key3);
- }
- }
- }
- void Timer0Interrupt() interrupt 1 {
- static u16 ms;
- static u8 K1ms, K2ms, K3ms;
- TH0 = TH_1ms;
- TL0 = TL_1ms;
- if (sKey1) {
- K1ms = 0;
- } else {
- if (K1ms != 0xFF) {
- K1ms++;
- }
- }
- if (sKey2) {
- K2ms = 0;
- } else {
- if (K2ms != 0xFF) {
- K2ms++;
- }
- }
- if (sKey3) {
- K3ms = 0;
- } else {
- if (K3ms != 0xFF) {
- K3ms++;
- }
- }
- Key1 = !(K1ms >= KEY_TIME);
- Key2 = !(K2ms >= KEY_TIME);
- Key3 = !(K3ms >= KEY_TIME);
- if (++ms >= 100) {
- ms = 0;
- switch (flag) {
- case 1:led = _crol_(led, 1); break;
- case 2:led = _cror_(led, 1); break;
- }
- }
- P0 = ~led;
- }
復制代碼 |