定时器操控LED灯
原理其实就是时钟->计数器->中断系统
分别给他赋值即可
#include <REGX52.H>
void Timer0_Init()
{
//TMOD = 0x01;
TMOD = TMOD & 0xF0;
TMOD = TMOD | 0x01;
TF0 = 0;
TR0 = 1;
TH0 = 64535 / 256;//取高八位
TL0 = 64535 % 256;//取低八位
ET0 = 1;
EA = 1;
PT0 = 0;
}
unsigned int cnt = 0;
void Timer0_Routine() interrupt 1
{
//这里主要是将数据还原用的
TH0 = 64535 / 256;
TL0 = 64535 % 256;
cnt++;
if(cnt >= 1000)
{
cnt = 0;
P2_0 = ~P2_0;
}
}
void main()
{
Timer0_Init();
while(1)
{
}
}
定时器实现流水灯操作
main函数部分
#include <REGX52.H>
#include "key.h"
#include "Timer0Init.h"
#include <INTRINS.h>
//unsigned int cnt = 0;
unsigned int LED_MODE;
void Timer0_Routine() interrupt 1
{
static unsigned int cnt;
TL0 = 0x18;
TH0 = 0xFC;
cnt++;
if(cnt >= 200)
{
cnt = 0;
if(LED_MODE == 0)
{
P2 = _crol_(P2,1);
}
if(LED_MODE == 1)
{
P2 = _cror_(P2,1);
}
}
}
void main()
{
P2 = 0xFE;
Timer0Init();
while(1)
{
unsigned char key;
//unsigned int LED_MODE;
key = KeyNum();
if(key)
{
if(key == 1)
{
LED_MODE++;
if(LED_MODE >= 2)LED_MODE = 0;
}
}
}
}
各个分函数
定时器
#include <REGX52.H>
void Timer0Init()
{
TMOD &= 0xF0;
TMOD |= 0x01;
TL0 = 0x18;
TH0 = 0xFC;
TF0 = 0;
TR0 = 1;
ET0 = 1;
EA = 1;
PT0 = 0;
}
按键代码
#include <REGX52.H>
#include "delay.h"
unsigned char key = 0;
unsigned char KeyNum()
{
if(P3_1 == 0){Delay1ms(20);while(P3_1 == 0);Delay1ms(20);key = 1;}
if(P3_0 == 0){Delay1ms(20);while(P3_0 == 0);Delay1ms(20);key = 2;}
if(P3_2 == 0){Delay1ms(20);while(P3_2 == 0);Delay1ms(20);key = 3;}
if(P3_3 == 0){Delay1ms(20);while(P3_3 == 0);Delay1ms(20);key = 4;}
return key;
}
定时器制作
main函数
#include <REGX52.H>
#include "LCD1602.h"
#include "delay.h"
#include "Timer0Init.h"
unsigned int hour1,min1,sec1;
void Timer0_Routine() interrupt 1
{
static unsigned int cnt;
TL0 = 0x18;
TH0 = 0xFC;
cnt++;
if(cnt >= 1000)
{
cnt = 0;
sec1++;
if(sec1 >= 60)
{
sec1 = 0;
min1++;
if(min1 >= 60)
{
min1 = 0;
hour1++;
if(hour1 >= 24)
{
hour1 = 0;
}
}
}
}
}
void main()
{
LCD_Init();
Timer0Init();
LCD_ShowString(1,1,"Clock:");
LCD_ShowString(2,1," : :");
while(1)
{
LCD_ShowNum(2,1,hour1,2);
LCD_ShowNum(2,4,min1,2);
LCD_ShowNum(2,7,sec1,2);
}
}
定时器设置
#include <REGX52.H>
void Timer0Init()
{
TMOD &= 0xF0;
TMOD |= 0x01;
TL0 = 0x18;
TH0 = 0xFC;
TF0 = 0;
TR0 = 1;
ET0 = 1;
EA = 1;
PT0 = 0;
}