定时器中断控制led灯:
#include "timer0.h"
#include <REG52.h>
#include "delay.h"sbit LED = P1^0;
void Timer0_Init()
{TMOD &=0xF0; //高四位不变,低四位清零TMOD |= 0x01; //高四位不变,低四位最后一位置1(定时器0模式1)TF0 = 0; //关闭中断溢出标志位TR0 = 1; //开启定时器0TH0 = 64535/256;//高八位TL0 = 64535%256;//低八位ET0 = 1; //打开定时器0中断EA = 1; //打开总中断PT0 = 1; //中断优先级}
void Timer0_Routine() interrupt 1//配置中断函数{static unsigned int Tcount;TH0 = 64535/256;TL0 = 64535%256;//计数器从64535开始计数,中断一次为1msTcount++;if(Tcount >= 1000)//每过1s{ LED = 0;Delay500ms();LED = 1;Delay500ms();//灯亮0.5s灭0.5s}}
串口中断控制引脚高低电平:
51单片机的串口模块没有独立的波特率发生器,所以要通过配置定时器作为串口波特率发生器
#include "uart.h"
#include <REG52.h>void UART_Init()
{SCON = 0x50; //串口配置寄存器PCON = 0x80; //配置波特率加倍TMOD &=0x0F; //高四位清零低四位不变TMOD |= 0x20; //选择定时器1模式3TR1 = 1; //开启定时器1TL1 = 0xF4; TH1 = 0xF4; //配置波特率ET1 =0; //关闭定时器1中断ES = 1; //开启串行口中断EA = 1; //开启总中断}void UART_SendByte(unsigned char Byte)//串口发送字节函数
{SBUF = Byte;while(TI == 0); //TI为发送中断请求标志位置1代表发送数据第8位结束TI == 0;}
void UART_Routine() interrupt 4
{if (RI == 1) //RI为接收中断请求标志位{P1 = SBUF; //控制引脚电平,SBUF=1,则p1引脚为高电平UART_SendByte(SBUF);RI = 0;}}