#include <hidef.h> /* common defines and macros */ #include <mc9s12e128.h> /* derivative information */ #include <S12E128Bits.h> #include "S12eVec.h" #include <stdio.h> #include "Pins.h" #define TIME_TO_TICKS_100 75 //multiple us to ticks /100 (.75 ticks/us) #define TIME_TO_DISTANCE 58 //divide us to cm #define OUTPUT_TIME 8 //10 us static unsigned int FrontRiseTime; static unsigned int FrontFallTime; static unsigned int FrontDistance; static unsigned int BackRiseTime; static unsigned int BackFallTime; static unsigned int BackDistance; /* Ultrasonic on Timer , Channels 4-7 */ void InitUltrasonic(void) { FrontRiseTime = 0; FrontFallTime = 0; FrontDistance = 0; BackRiseTime = 0; BackFallTime = 0; BackDistance = 0; // Init Timer (%32) TIM1_TSCR1 |= _S12_TEN; TIM1_TSCR2 |= _S12_PR2 |_S12_PR0; TIM1_TSCR2 &= ~_S12_PR1; // FRONT SENSOR // Init Output Compare - Timer 0 Channel 6 TIM1_TIOS |= _S12_IOS6; TIM1_TFLG1 = _S12_C6F; // Set to clear at 10 us TIM1_TC6 = OUTPUT_TIME; TIM1_TCTL1 |= _S12_OM6; TIM1_TCTL1 &= ~_S12_OL6; // Toggle T5 on Overflow TIM1_TTOV |= _S12_TOV6; // Init Input Caputure - Channel 7 TIM1_TIOS &= ~_S12_IOS7; // Enable Interrupt TIM1_TIE |= _S12_C7F; // Clear Flag TIM1_TFLG1 = _S12_C7F; // All Edges TIM1_TCTL3 |= _S12_EDG7A |_S12_EDG7B; // BACK SENSOR // Init Output Compare - Timer 0 Channel 4 TIM1_TIOS |= _S12_IOS4; TIM1_TFLG1 = _S12_C4F; // Set to clear at 10 us TIM1_TC4 = OUTPUT_TIME; TIM1_TCTL1 |= _S12_OM4; TIM1_TCTL1 &= ~_S12_OL4; // Toggle T5 on Overflow TIM1_TTOV |= _S12_TOV4; // Init Input Caputure - Channel 5 TIM1_TIOS &= ~_S12_IOS5; // Enable Interrupt TIM1_TIE |= _S12_C5F; // Clear Flag TIM1_TFLG1 = _S12_C5F; // All Edges TIM1_TCTL3 |= _S12_EDG5A |_S12_EDG5B; // Enable Interrupts EnableInterrupts; //Initialize Input Capture as Input DDR_ULTRASONIC &= ~(PIN_FRONT_ECHO | PIN_BACK_ECHO); } //Front Sensor Input Capture Interrupt Response Routine - Channel 5 void interrupt _Vec_tim1ch5 FrontEcho(void){ // If rising edge if((PORT_ULTRASONIC & PIN_FRONT_ECHO) == PIN_FRONT_ECHO){ // Save as rising edge time FrontRiseTime = TIMER_FRONT_ECHO; } // If falling edge else{ // Save as falling edge FrontFallTime = TIMER_FRONT_ECHO; // Calculate pulse width FrontDistance = (FrontFallTime - FrontRiseTime)/TIME_TO_TICKS_100*100/TIME_TO_DISTANCE; } //Clear flag TIM1_TFLG1 = _S12_C5F; } //Back Sensor Input Capture Interrupt Response Routine - Channel 7 void interrupt _Vec_tim1ch7 BackEcho(void){ // If rising edge if((PORT_ULTRASONIC & PIN_BACK_ECHO) == PIN_BACK_ECHO){ // Save as rising edge time BackRiseTime = TIMER_BACK_ECHO; } // If falling edge else{ // Save as falling edge BackFallTime = TIMER_BACK_ECHO; // Calculate pulse width BackDistance = (BackFallTime - BackRiseTime)/TIME_TO_TICKS_100*100/TIME_TO_DISTANCE; } //Clear flag TIM1_TFLG1 = _S12_C7F; } unsigned int QueryFrontDistance(void){ return FrontDistance; } unsigned int QueryBackDistance(void){ return BackDistance; }