Timer0.h
#ifndef __Timer0_H__
#define __Timer0_H__
void Timer0Init(void);
#endif
Timer0.c
#include <STC89C5xRC.H>
void Timer0Init(void)
{
AUXR &= 0x7F;
TMOD &= 0xF0;
TMOD |= 0x01;
TL0 = 0x18;
TH0 = 0xFC;
TF0 = 0;
TR0 = 1;
ET0 = 1;
EA = 1;
PT0 = 0;
}
main.c
#include <STC89C5xRC.H>
#include "Timer0.h"
void main(){
Timer0Init();
while(1){
}
}
unsigned char arr[] = {0xFE,0xFD,0xFB,0xF7,0xEF,0xDF,0xBF,0x7F};
unsigned char index = 0;
void Timee0_Routine() interrupt 1{
static unsigned int T0Count = 0;
TL0 = 0x18;
TH0 = 0xFC;
T0Count++;
if(T0Count >= 1000){
T0Count = 0;
P2 = arr[index];
index++;
if(index == 8)
index = 0;
}
}
首先体验了一下中断,就是主程序是一个while()循环,通过设置就会每隔一秒钟产生一次中断,产生中断就会停下当前的主程序,转而执行你写的中断服务子程序,执行完毕再回来执行主程序。
实验一
按下独立按键K1,流水灯方向向左流动 按下独立按键K2,流水灯方向向右流动
Timer0在上面展示过了,Delay也不展示了。 key.h
#ifndef __Key_H__
#define __Key_H__
unsigned char Key();
#endif
Key.c
#include <STC89C5xRC.H>
#include "Delay.h"
unsigned char Key(){
unsigned char KeyNumber = 0;
if(P31 == 0){Delay(20);while(P31 == 0);Delay(20);KeyNumber = 1;}
if(P30 == 0){Delay(20);while(P30 == 0);Delay(20);KeyNumber = 2;}
if(P32 == 0){Delay(20);while(P32 == 0);Delay(20);KeyNumber = 3;}
if(P33 == 0){Delay(20);while(P33 == 0);Delay(20);KeyNumber = 4;}
return KeyNumber;
}
main.c
#include <STC89C5xRC.H>
#include "Timer0.h"
#include "INTRINS.h"
#include "Key.h"
unsigned char KeyNum,LEDMode;
void main(){
Timer0Init();
P2 = 0xFE;
LEDMode = 0;
while(1){
KeyNum = Key();
if(KeyNum){
if(KeyNum == 1){
LEDMode = 0;
}
else if(KeyNum == 2){
LEDMode = 1;
}
}
}
}
void Timee0_Routine() interrupt 1{
static unsigned int T0Count = 0;
TL0 = 0x18;
TH0 = 0xFC;
T0Count++;
if(T0Count >= 1000){
T0Count = 0;
if(LEDMode){
P2 = _cror_(P2,1);
}
else{
P2 = _crol_(P2,1);
}
}
}
总结: 如何判别每个独立按键的按下? 通过写一个函数,当每个按键按下,返回一个数字。 通过判断不同数字判断对应按键的按下。
实验二
实现一个计时器
#include <STC89C5xRC.H>
#include "Timer0.h"
#include "LCD1602.h"
unsigned int hour,minute,second;
void main(){
LCD_Init();
LCD_ShowString(1,1,"Clock!");
hour = minute = second = 0;
Timer0Init();
while(1){
LCD_ShowNum(2,1,hour,2);
LCD_ShowString(2,3,":");
LCD_ShowNum(2,4,minute,2);
LCD_ShowString(2,6,":");
LCD_ShowNum(2,7,second,2);
}
}
void Timee0_Routine() interrupt 1{
static unsigned int T0Count = 0;
TL0 = 0x18;
TH0 = 0xFC;
T0Count++;
if(T0Count >= 1000){
T0Count = 0;
second++;
if(second == 60){
second = 0;
minute++;
}
if(minute == 60){
minute = 0;
hour++;
}
if(hour == 24){
hour = 0;
}
}
}
|