当前位置: 首页 > news >正文

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

 

 


http://www.mrgr.cn/news/33107.html

相关文章:

  • 一个安卓鸿蒙化工具
  • 银河麒麟桌面操作系统V10(SP1)离线升级SSH(OpenSSH)服务
  • CompletableFuture的allOf一定不要乱用!血泪史复盘
  • 01-ZYNQ linux开发环境安装,基于Petalinux2023.2和Vitis2023.2
  • go 安装依赖超时
  • msvcp140.dll0丢失的解决方法,总结6种靠谱的解决方法
  • Spring Boot实战:使用策略模式优化商品推荐系统
  • 数据结构:内部排序
  • Spring Boot实战:使用@Import进行业务模块自动化装配
  • Jboss Administration Console弱⼝令
  • 2024年华为杯-研赛F题论文问题一二讲解+代码分享
  • 计算机毕业设计 基于Python的校园个人闲置物品换购平台 闲置物品交易平台 Python+Django+Vue 前后端分离 附源码 讲解 文档
  • Vision Transformer (ViT)、Swin Transformer 和 Focal Transformer
  • 9、等保测评介绍
  • (项目管理系列课程)项目启动阶段:项目整合管理-制定项目章程
  • 【RabbitMQ】消息分发、事务
  • 【MySQL】 索引
  • JVM 调优篇9 调优案例6- cpu使用过载解决办法【超赞】
  • 京东-第2题-撞车
  • 机器学习——Stacking