最近做项目,写了一个硬件延时代码,喜欢的朋友请拷贝,评论一下,让我高兴一下好不
/*---------------------------------------------------------------------*/ /* --- STC MCU Limited ------------------------------------------------*/ /* --- STC 1T Series MCU Demo Programme -------------------------------*/ /* --- Mobile: (86)13922805190 ----------------------------------------*/ /* --- Fax: 86-0513-55012956,55012947,55012969 -----------------------*/ /* --- Tel: 86-0513-55012928,55012929,55012966 ------------------------*/ /* --- Web: www.STCMCU.com --------------------------------------------*/ /* --- Web: www.GXWMCU.com --------------------------------------------*/ /* --- QQ: 800003751 -------------------------------------------------*/ /* 如果要在程序中使用此代码,请在程序中注明使用了STC的资料及程序 */ /*---------------------------------------------------------------------*/ #include "stc15wxx.h" #include "main.h" #include "pwm.h" #define Timer0_Rate_HZ (1000000) //中断频率,最小频率 FOSC/Timer0_Rate_HZ=65536,最大FOSC/Timer0_Rate_HZ=1 #if (Timer0_Rate_HZ >FOSC) #error "Timer0_Rate_HZ > FOSC !!!" #endif #define Timer0_Reload (65536UL -( FOSC/ Timer0_Rate_HZ)) //Timer 0 重装值 /**********************************************/ u8 flag; void time0_init(void) { AUXR |= (1<<7); // Timer0 set as 1T mode TMOD &= ~(1<<2); // Timer0 set as Timer TMOD &= ~0x03; // Timer0 set as 16 bits Auto Reload TH0 = 0 / 256; //Timer0 Load TL0 = 0 % 256; ET0 = 0; //Timer0 Interrupt Disable PT0 = 0; //高优先级 TR0 = 0; //Timer0 not Run EA = 1; //打开总中断 } void timer0 (void) interrupt 1 { flag = 0; ET0 = 0; TR0 = 0; } void timer_load(u16 load) { flag = 1; TH0 = load / 256; //Timer0 Load TL0 = load % 256; ET0 = 1; TR0 = 1; while(flag); } //递归延时函数 #define F_MHZ (24) //定义时钟是多少M void Hdelay_nus(u16 nus) { if(nus<=(65536/F_MHZ)) { timer_load(65536UL-F_MHZ*nus); return; } else { timer_load(65536%F_MHZ);//接近16位定时最大延时 nus -= (65536/F_MHZ); Hdelay_nus(nus); } } void Hdelay_nms(u16 nms) { while(nms--) { Hdelay_nus(1000-1); } }