本程序一共有3个文件下面分别列出:
main.c
#include "stc12c5a.h"
#include "type.h"
#define FRE 22118400
#define TIME_FRE10000 //计时1/10000=0.0001s=0.1ms(此时间是用来加快LED闪烁频率)
#define T0RELOAD(65536 - (FRE / TIME_FRE))
//***************************************初始化变量
volatile U32 SYS_TIME = 0;
volatile U32 LED_PWM = 0;
//*****************************************延时函数
void delay(U32 dly)
{
U32 i;
while(--dly > 0)
{
for(i=0;i++;i<1000000);
}
}
//****************************************定时器0初始化函数
void Timer0_Init()
{
TMOD &= 0XF0;
TMOD |= 0X01;//定时器0的16位计数方式
TH0 = T0RELOAD / 256;
TL0 = T0RELOAD % 256;
AUXR |= 0X80;// 计数器0时钟为Fosc,即1T
PT0 = 1;// 定时器0优先级控制位, 1 为高优先级 0 为低优先级
EA = 1;//开总中断
ET0 = 1;//开定时器0中断
TR0 = 1;//启动定时器0
}
//*****************************************主函数
void main()
{
Timer0_Init();
//以下根据实际情况修改程序
while(1)
{
P33 = 1;
if(P33 == 0)// KEY1
{
delay(5000);
if(P33 == 0)
{
LED_PWM = 0;// 熄灭LED
}
}
P34 = 1;
if(P34 == 0)// KEY2 按键一直按着,KED逐渐变亮
{
delay(5000);
if(P34 == 0)
{
if(LED_PWM < 100)
LED_PWM ++;
}
}
P35 = 1;
if(P35 == 0)// KEY3 按键一直按着,KED逐渐变暗
{
delay(5000);
if(P35 == 0)
{
if(LED_PWM >0)
LED_PWM --;
}
}
}
}
//*****************************************定时器0中断
void Timer0_Routine() interrupt 1
{
TH0 = T0RELOAD / 256;
TL0 = T0RELOAD % 256;
//以下根据实际情况修改程序
SYS_TIME ++;
if(SYS_TIME < LED_PWM)
{
P0 = 0;//点亮LED
}
else
{
P0 = 0XFF;//关闭LED
}
if(SYS_TIME > 100)
{SYS_TIME = 0;}
}
type.h
#ifndef _TYPE_H_
#define _TYPE_H_
typedef unsigned char U8;
typedef signed char S8;
typedef unsigned int U16;
typedef signed int S16;
typedef unsigned long U32;
typedef signed long S32;
#endif