学习记录(第七课) 按键控制LED灯 按键的种类有轻触开关、自复位、自锁,封装有贴片、直插等等 常见的轻触开关内部结构:由下图可见,是有塑胶按钮、窝仔片、金属触点等组成。按下后就导通,松手触点就断开。 但要想在单片机中控制就不可避免的出现抖动问题,消抖就的方式常见有2种,一种是利用硬件消抖,还有一种是在软件写延时程序多次判断按键是否按下来进行软件消抖。 /***** main主函数 *****/ #include <STC32G.H> #include "KEY.H" #include "DELAY.H"
unsigned char Key_Num; void sys_init();
void main() { unsigned char LED_DATA=0XFE; sys_init(); P6=LED_DATA; while(1) { // /***** 上升沿动作 *****/ // Key_Num=Key(); // if(Key_Num==1) // { // P40=0;//LED灯组低电平使能 // P60=!P60;// // while(Key_Num==1); // } /***** 下降沿动作 *****/ Key_Num=Key(); if(Key_Num==1)//判断P34口按键按下? { P40=0;//LED灯组低电平使能 LED_DATA=((LED_DATA<<1)+1); if(LED_DATA==0xFF) LED_DATA=0xFE; P6=LED_DATA; while(Key_Num==1); } if(Key_Num==2)//判断P35口按键按下? { P40=0;//LED灯组低电平使能 P61=0;//将P6.1灯点亮 } } }
void sys_init() { WTST = 0; //设置程序指令延时参数,赋值为0可将CPU执行指令的速度设置为最快 EAXFR = 1; //扩展寄存器(XFR)访问使能 CKCON = 0; //提高访问XRAM速度
P0M1 = 0x00; P0M0 = 0x00; //设置为准双向口 P1M1 = 0x00; P1M0 = 0x00; //设置为准双向口 P2M1 = 0x00; P2M0 = 0x00; //设置为准双向口 P3M1 = 0x00; P3M0 = 0x00; //设置为准双向口 P4M1 = 0x00; P4M0 = 0x00; //设置为准双向口 P5M1 = 0x00; P5M0 = 0x00; //设置为准双向口 P6M1 = 0x00; P6M0 = 0x00; //设置为准双向口 P7M1 = 0x00; P7M0 = 0x00; //设置为准双向口 } /***** Key.c *****/ #include <STC32G.H> #include "DELAY.H" unsigned char Key() { unsigned char KeyNumber=0; if(P34==0){Delay_ms(10);while(P34==0);Delay_ms(10);KeyNumber=1;}//延时消抖再判断P34按键是否按下,按下KeyNumber返回1 if(P35==0){Delay_ms(10);while(P35==0);Delay_ms(10);KeyNumber=2;}//延时消抖再判断P34按键是否按下,按下KeyNumber返回2
return KeyNumber; } /***** Key.h *****/
#ifndef _KEY_H_ #define _KEY_H_
unsigned char Key();
#endif /***** Delay .c *****/
#include <STC32G.H>
#define MAIN_Fosc 24000000UL void Delay_ms(unsigned int ms) //定义一个无符号整型变量ms { unsigned int i; //定义一个无符号整型变量i do { i=MAIN_Fosc/6000;//系统时钟的6分频 while(--i); }while(--ms); } /***** Delay.h *****/
#ifndef _Delay_ms_H_ #define _Delay_ms_H_
void Delay_ms(unsigned int xms);
#endif
|