#include <hidef.h> /* common defines and macros */ #include <MC9S12XS128.h> /* derivative information */ #pragma LINK_INFO DERIVATIVE"mc9s12xs128" /*可以通过更改TIMER的值来实现不同时间的定时, 定时长为TIMER *10us*/ #define TIMER 1 #define TRING PORTA_PA0 //控制端 #define ECHO PORTA_PA1 //接收端 ulong time = 0; /* n * 10us延时*/ void Delay_Us(ulong n) { time = n; while (time); } /*IO口初始化*/ void IO_Init(void) { DDRA = 0x01; //A0输出,A1输入 } /*PIT初始化,实现10US定时*/ void PIT_Init(void) { PITCFLMT_PITE = 0; //定时中断通道0关 PITCE_PCE0 = 1; //定时器通道0使能 PITMTLD0 = 160 - 1; //8位定时器初值设定,160分频 PITLD0 = TIMER - 1; //16位定时器初值设定,TIMER*10us PITINTE_PINTE0 = 1; //定时器中断通道0中断使能 PITCFLMT_PITE = 1; //定时器通道0使能 } void main(void) { ulong t; double dis; IO_Init(); //IO初始化 PIT_Init(); //PIT初始化 EnableInterrupts; //开中断 /*等待200us使超声波模块初始化完毕*/ Delay_Us(20); while (1) { /*给控制端一个超过10US的高电平,然后置低*/ TRING = 1; Delay_Us(2); TRING = 0; /*等待接收端产生高电平并计时*/ while (!ECHO); time = 0xff; while (ECHO); t = 0xff - time; //计时 dis = 1.7 * t; //计算距离 //延时10MS,这个的原因大家看时序图,不同的硬件不同 Delay_Us(1000); } } /*PIT定时中断*/ #pragma CODE_SEG __NEAR_SEG NON_BANKED void interrupt 66 PIT0(void) { PITTF_PTF0 = 1; //清中断标志位 --time; } |