一、独立按键
例如使用四个按键分别控制四个LED
#include <stc8.H>//头文件,根据所使用的MCU确定
#include <intrins.h>
sbit KEY_1 = P3^2;//定义引脚
sbit KEY_2 = P3^3;
sbit KEY_3 = P3^4;
sbit KEY_4 = P3^5;//key1-4 refers to four bottons
sbit LED_1 = P6^0;
sbit LED_2 = P6^1;
sbit LED_3 = P6^2;
sbit LED_4 = P6^3;//led1-4 referes to four leds
bit keysta = 1;
bit backup = 1;
void Timer0() interrupt 1//设置定时器
{
TH0 = (65536-10000)/256;
TL0 = (65536-10000)%256;
TR0 = 0;
if(KEY_1 == 0)
{
LED_1 = ~LED_1;
while(KEY_1 == 0);
}
if(KEY_2 == 0)
{
LED_2 = ~LED_2;
while(KEY_2 == 0);
}
if(KEY_3 == 0)
{
LED_3 = ~LED_3;
while(KEY_3 == 0);
}
if(KEY_4 == 0)
{
LED_4 = ~LED_4;
while(KEY_4 == 0);
}
}
void main (void)
{
TMOD|=0x01;
TH0 = (65536-10000)/256;
TL0 = (65536-10000)%256;
ET0 = 1;
EA = 1;
TR0 = 0;
while(1)
{
if(KEY_1 == 0)
{
TR0 = 1;
}
if(KEY_2 == 0)
{
TR0 = 1;
}
if(KEY_3 == 0)
{
TR0 = 1;
}
if(KEY_4 == 0)
{
TR0 = 1;
}
}
}
总结:
1、按键与LED对应即可,
2、要注意按键消抖通过设置定时器,每隔一段时间检测一次电位,连续几次 电位一致便可以得出按键当前的状态。
3、抖动形成的原因:按键的物理特性,按下去的一瞬间不可能直接到达稳态,在按下与弹起的一瞬间会形成波动,波动会造成MCU的误判所以要消除抖动。