/* 
 * File:  ultrasonic.c
 * Project: Helmet.X
 * Author: Claire Chen and Mark Zhao
 */

#include "ultrasonic.h"

/**
 * Set up necessary hardware for sensor. 
 * 
 * Timer 3 is reserved for ultrasonic 
 * (both sending 10us pulse and measuring input pulse)
 * 
 */
void init_ultrasonic(void){
   //Setup timer 3 for ultrasonic 
  OpenTimer3(T3_ON | T3_SOURCE_INT | T3_PS_1_64, 0xffff);
  
  // Configure RPB13 for output compare 4, to send 10us trigger pulse
  PPSOutput(3,RPB13,OC4);

  // Configure RPA2 for input capture 1
  //Configure input capture for rising edge
  OpenCapture1(IC_ON | IC_INT_1CAPTURE | IC_TIMER3_SRC | IC_EVERY_EDGE);
  ConfigIntCapture1(IC_INT_ON | IC_INT_PRIOR_3 | IC_INT_SUB_PRIOR_3);
  INTClearFlag(INT_IC1); //Clear the interrupt
  PPSInput(3, IC1, RPA2);  
}

void send_pulse(void){

  // Output 10us pulse
  OpenOC4(OC_ON | OC_TIMER3_SRC | OC_SINGLE_PULSE, 7, 0);
  
  // Reset timer
  WriteTimer3(0x0000);

}

