1 定时器0、1
模块Time01.c 代码
#include <REGX52.H>
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1000个1ms是1s,10ms中断的话,1000改成100
void Time0_init(void) //1毫秒@11.0592MHz
{
TMOD &= 0xF0; //设置定时器016位模式
TMOD |= 0x01; //设置定时器0模式
TL0 = T1MS; //initial timer0 low byte
TH0 = T1MS >> 8; //initial timer0 high byte
TF0 = 0; //清除TF0标志
ET0=1;
EA=1;
PT0=0;
TR0 = 1; //定时器0开始计时
}
/* 主程序main.c代码
#include <REGX52.H>
#include "Time01.h"
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1000个1ms是1s,10ms中断的话,1000改成100
void main()
{
Time0_init();
while(1)
{
}
}
void Timer0_Routine() interrupt 1
{
static unsigned int T0Count;
TL0 = T1MS; //reload timer0 low byte
TH0 = T1MS >> 8; //设置定时初始值
T0Count++;
if(T0Count>=1000)
{
T0Count=0;
P2=~P2;//执行代码
}
}
//头文件Time01.h代码
#ifndef __TIME01_H__
#define __TIME01_H__
void Time0_Init(void);
#endif
*/
2 定时器2
模块Time2.c 代码
#include <REGX52.H>
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1000个1ms是1s,10ms中断的话,1000改成100
void Time2_init()
{
T2MOD = 0; //初始化模式寄存器,16位重装
T2CON = 0;
RCAP2L = TL2 = T1MS; //initial timer2 low byte
RCAP2H = TH2 = T1MS >> 8; //initial timer2 high byte
ET2 = 1; //enable timer2 interrupt
EA = 1; //open global interrupt switch
TR2 = 1; //timer2 start running
}
/* 主程序main.c代码
#include <REGX52.H>
#include "Time2.h"
#define FOSC 11059200L
#define T1MS (65536-FOSC/12/1000) //1000个1ms是1s,10ms中断的话,1000改成100
void main()
{
Time2_init();
while(1)
{
}
}
void tm2_isr() interrupt 5
{
static unsigned int count;
TF2 = 0;
if (count-- == 0) //1ms * 1000 -> 1s
{
count = 1000; //reset counter
P2=~P2;//执行代码
}
}
//头文件Time2.h代码
#ifndef __TIME2_H__
#define __TIME2_H__
void Time2_init();
#endif
*/
3 定时器1串口
Time1Uart.c
#include <REGX52.H>
void Time1Uart_Init()
{
SCON=0x50; //SM0 SM1为方式1,8位UART。REN为1,允许接收。TI RI为0
PCON &= 0x80; //SMOD保持不变为0,波特率不加倍。
TMOD &= 0x0F; //设置定时器1模式,不影响定时器0
TMOD |= 0x20; //设置定时器1,8位重装
TL1 = 0xFA; //设定定时初值 4800波特率,11.0592MHz
TH1 = 0xFA; //设定定时器重装值
ET1 = 0; //禁止定时器1中断
TR1 = 1; //启动定时器1
EA=1; //打开总中断
ES=1; //打开串口中断
}
void Uart_SendByte(unsigned char Byte) //发送一字节
{
SBUF=Byte;
while(TI==0);
TI=0;
}
void Uart_SendString(char *s) //发送字符串,实参如"sun wen ping."
{
while (*s) //Check the end of the string
{
Uart_SendByte(*s++); //Send current char and increment string ptr
}
}
/*
//main.c程序
#include <REGX52.H>
#include "Time1Uart.h"
void main()
{
Time1Uart_init();
Uart_SendString("sun wen ping!");
Uart_SendByte(0x66);
while(1)
{
}
}
void UART_Routine() interrupt 4 // 函数名任意,interrupt 4 标明是串口中断处理程序
{
if (RI) //利用TI发送的程序,参见Time2Uart.c
{
RI = 0; //Clear receive interrupt flag
P2 = SBUF; //P2 show UART data
}
}
//头文件Time1Uart.h
#ifndef __TIME1UART_H__
#define __TIME1UART_H__
void Time1Uart_Init();
void Uart_SendByte(unsigned char Byte);
void Uart_SendString(char *s);
#endif
*/
4 定时器2串口
Time2Uart.c
#include <REGX52.H>
#include "intrins.h"
#define FOSC 11059200L //时钟频率
#define BAUD 4800 //UART 波特率
#define NONE_PARITY 0 //无奇偶校验