51单片机——独立按键

 一、独立按键对应单片机P3管脚,如图

96c23b692b47488997db4871c9acbc50.jpg

 二、按键点亮LED灯

#include <STC89C5xRC.H>

void main()

{

 while(1)

 {

  if(P30==0)

  {

   P20=0;

  }

  else

  {

   P20=1;

  }

 }

}

当按键为0时,代表按下,所以当P30按下时,让P20=0(亮)

 

三、按下后松开点亮LED灯

#include <STC89C5xRC.H>

void Delay(unsigned int xms) //@12.000MHz

{

 unsigned char i, j;

 while(xms)

 {

 i = 2;

 j = 239;

 do

 {

  while (--j);

 } while (--i);

 xms--;

 }

}

void main()

{

 while(1)

 {

  if(P31==0)

  {

   Delay(20); // Keys away shaking

   while(P31==0);

   Delay(20); // Detection of let go

   P20=~P20;

  }

 }

}

独立按键按下时是有抖动的,为了防止抖动产生影响,所以给按键加上延迟。(Delay(20))

当P31按下时,产生抖动,延迟20ms。如果不松,P31一直是0,陷入死循环。

当P31不等于0时,代表松开了,产生抖动,延迟20ms。

因为P20之前默认是1(高电平),通过取反,实现P20由高电平转为低电平,P20灯变亮。

当再次按下松开时,又变为高电平,灯灭。

 

四、按键实现LED灯二进制表示

#include <STC89C5xRC.H>
 
void Delay(unsigned int xms)        //@12.000MHz
{
    unsigned char i, j;
    while(xms)
    {
    i = 2;
    j = 239;
    do
    {
        while (--j);
    } while (--i);
    xms--;
    }
}
 
void main()
{
    unsigned char LEDNum=0;  // char max num is 255
    while(1)
    {
    if(P31==0)
    {
        Delay(20);
        while(P31==0);
        Delay(20);
        LEDNum++;
        P2=~LEDNum;
    }
    }
}

当P31按下时,产生抖动,延迟20ms。

如果不松,陷入死循环。

松开时,产生抖动,延迟20ms。

char类型占1个字节(8bit),一开始默认为0000 0000。

松开按键后,加一,变为0000 0001,赋值给P2,使P20亮。

再次执行后,再加一,变为0000 0010,赋值给P2,使P21亮。

再次执行后,再加一,变为0000 0011,赋值给P2,使P20和P21亮。

。。。。

实现二进制表示。

五、通过按键实现灯左移右移

#include <STC89C5xRC.H>

void Delay(unsigned int xms); // must statement

 

unsigned char LEDNum; // The global variable

 

void main()

{

    P2=~0x01; //int P2

 while(1)

 {

  if(P31==0)

  {

  Delay(20);

  while(P31==0);

  Delay(20);

  LEDNum++;

  if(LEDNum>=8)

   LEDNum=0;

  P2=~(0x01<<LEDNum); // 0x01 of P2 need shift to the left LEDNum, and get the not

  }

  if(P30==0)

  {

  Delay(20);

  while(P30==0);

  Delay(20);

  if(LEDNum==0)

   LEDNum=7;

  else

   LEDNum--;

  P2=~(0x01<<LEDNum);

  }

 }

}

 

void Delay(unsigned int xms) //@12.000MHz

{

 unsigned char i, j;

 while(xms)

 {

 i = 2;

 j = 239;

 do

 {

  while (--j);

 } while (--i);

 xms--;

 }

}

一开始让P20亮,然后通过控制P30和P31,实现左移和右移。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值