#include <htc.h>
__CONFIG(LVP_OFF & BOREN_OFF & PWRTE_ON & WDTE_OFF & FOSC_HS);
#define _XTAL_FREQ 20000000
main(){
TRISB = 0b00010000;
RB5=1;
__delay_ms(1000);
RB5=0;
__delay_ms(500);
RB5=1;
__delay_ms(1000);
RB5=0;
__delay_ms(500);
while(1){
int a;
T1CON = 0x10; //Initialize Timer Module
TMR1H = 0; //Sets the Initial Value of Timer
TMR1L = 0; //Sets the Initial Value of Timer
RB0 = 1; //TRIGGER HIGH
__delay_us(10); //10uS Delay
RB0 = 0; //TRIGGER LOW
while(!RB4); //Waiting for Echo
TMR1ON=1; //Timer Starts
while(RB4); //Waiting for Echo goes LOW
TMR1ON=0; //Timer Stops
a = (TMR1L | (TMR1H<<8)); //Reads Timer Value
a = a/58; //Converts Time to Distance
a = a + 1; //Distance Calibration
if(a>=2 && a<=400) //Check whether the result is valid or not
{
RB5=1;
}
else
{
RB5=0;
}
__delay_ms(400);
}
}