单片机C语言按键开关程序

单片机C语言按键开关程序,第1张

#include<reg52.h>

#define uint unsigned int

#define uchar unsigned char

void delay_ms(uint)

sbit led0=P0^0

sbit led1=P0^1

sbit key1=P3^2

sbit key2=P3^3

void main()

{

   uchar i=0

   uchar j=0

    while(1)

    {

       if(key1==0)//按键1

       {

        delay_ms(10)

        if(key1==0)

        {

            i++

            i=i%2

            switch(i)

            {

                 case 0: led0=1 break//关小灯

                 case 1: led0=0 break//开小灯

                 default:  break

            }

        }

        while(!key1)

        }

        

        if(key2==0)//按键2

       {

        delay_ms(10)

        if(key2==0)

        {

            j++

            j=j%2

            switch(j)

            {

                 case 0: led1=1 break//关小灯

                 case 1: led1=0 break//开小灯

                 default:  break

            }

        }

        while(!key2)

        }

    }

}

void delay_ms(uint z)  //延时子程序

{  

uint x,y

for(x=zx>0x--)

for(y=110y>0y--)

}

四个按键,定义如下:

KEY1 BIT P3.0

KEY2 BIT P3.1

KEY3 BIT P3.2

KEY4 BIT P3.3

按键处理程序:

-----------------------------------

READ_KEY:

JBKEY1, K2

CALL DELAY

JBKEY1, K2

JNB KEY1, $

PUSH ACC

INC 75H

MOV A, 75H

CJNE A, #10, ZINT01

MOV 75H, #0

ZINT01:

POP ACC

JMP K_EXIT

---------------

K2: JBKEY2, K3

CALL DELAY

JBKEY2, K3

JNB KEY2, $

PUSH ACC

INC 76H

MOV A, 76H

CJNE A, #10, ZINT01

MOV 76H, #0

ZINT01:

POP ACC

JMP K_EXIT

---------------

K3: JBKEY3, K4

CALL DELAY

JBKEY3, K4

JNB KEY3, $

PUSH ACC

DEC 75H

MOV A, 75H

CJNE A, #255, ZINT03

MOV 75H, #9

ZINT03:

POP ACC

JMP K_EXIT

---------------

K4: JBKEY4, K_EXIT

CALL DELAY

JBKEY4, K_EXIT

JNB KEY4, $

PUSH ACC

DEC 76H

MOV A, 76H

CJNE A, #255, ZINT04

MOV 76H, #9

ZINT04:

POP ACC

K_EXIT:

RET

---------------

DELAY:

DJNZ R7, $

DJNZ R7, $

RET

-----------------------------------

一个按键时程序如下:

while(1)

{

if(key==0)//按键按下

{ delayms(20)//延时消抖

if(key==0)//再次判断按键是否按下

{

while(key==0)//按键没有抬起

{ led=!leddelayms(200)}//LED闪烁

}

}

else led=0

}


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/11770172.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存