#include<p18f1330.h>
#include<delays.h>
#include <math.h>
#pragma config WDT=OFF
#pragma config OSC=INTIO2
#pragma config PWRT=ON
unsigned int a;
unsigned int time;
void main()
{
OSCCONbits.IRCF2 = 1;// 4mhz OSC
OSCCONbits.IRCF1 = 1;//
OSCCONbits.IRCF0 = 0;//
TRISBbits.TRISB4=0; // trig
TRISBbits.TRISB5=1; //echo
TRISAbits.TRISA2=0; //RED led
TRISAbits.TRISA3=0; //GREEN led
while(1)
{
PORTBbits.RB4=0;
PORTBbits.RB5=0;
PORTAbits.RA2=0;
PORTAbits.RA3=0;
TMR1H= 0;
TMR1L= 0;
PORTBbits.RB4=1;
Delay10TCYx(1);
PORTBbits.RB4=0;
while(PORTBbits.RB5 == 0); //If ECHO is HIGH
T1CONbits.TMR1ON = 1; //Start Timer
while(PORTBbits.RB5 == 1); //If ECHO is LOW
T1CONbits.TMR1ON = 0; //Stop Timer
// a = (TMR1L | (TMR1H<<8))/58.82; //Calculate Distance
//Delay10KTCYx(255);
//Delay10KTCYx(255);
time= TMR1H;
time= time<<8;
time= time|TMR1L;
a = time/58;
PIR1bits.TMR1IF=0;
Delay10TCYx(60);
//Delay10KTCYx(255);
//Delay10KTCYx(255);
if(a<=400)
{
PORTAbits.RA2=1; //red
}
if(a<=2000)
{
//PORTAbits.RA3=1; //green
LATAbits.LATA3=1;
}
//Delay10KTCYx(255);
}
}