自学内容网 自学内容网

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,实现左移和右移。

 

 


原文地址:https://blog.csdn.net/2301_80339607/article/details/142427871

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!