#include <p18f4580.h>
#include <delays.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#pragma config OSC= HS
#pragma config WDT=OFF
#pragma config LVP=OFF
#define Trig PORTBbits.RB3
#define Echo PORTBbits.RB2
void T0Delay10us(void);
void uart(void);
void Call_Init_PIC (void);
void sendPulse(void);
unsigned int distance ;
unsigned int time;
unsigned f,b;
void main(void)
{
TRISDbits.TRISD0=0;
Call_Init_PIC ();
uart();
while(1)
{
TMR1H= 0;
TMR1L= 0;
sendPulse();
while(Echo == 0);
T1CONbits.TMR1ON = 1;
while(Echo == 1);
T1CONbits.TMR1ON = 0;
time= TMR1H;
time= time<<8;
time= time|TMR1L;
//time = (TMR1L + (TMR1H<<8));
distance = time/28.8;
f=distance/10;
b=distance%10;
printf("\r\nDistance = %d.%d cm",f,b);
PIR1bits.TMR1IF=0;
Delay10KTCYx(255);
/*
if(distance>=0 && distance<=250)
{
LATDbits.LATD0=1;
}
else if(distance>=251 && distance<=500)
{
LATDbits.LATD0=1;
Delay10KTCYx(25);
LATDbits.LATD0=0;
}
else if (distance>=501 && distance<=1000)
{
LATDbits.LATD0=1;
Delay10KTCYx(25);
Delay10KTCYx(25);
Delay10KTCYx(25);
LATDbits.LATD0=0;
}
else
{
}
*/
}
}
void Call_Init_PIC (void)
{
TRISBbits.TRISB3=0;
TRISBbits.TRISB2=1;
}
void uart(void)
{
TXSTA=0B00100000;
SPBRG=32;
TRISCbits.RC6=0;
RCSTAbits.SPEN=1;
}
void sendPulse(void)
{
Trig=0;
Delay10KTCYx(255);
Trig=1;
T0Delay10us();
Trig=0;
}
void T0Delay10us()
{
T0CON=0x08;
TMR0H=0XFF;
TMR0L=0XCE;
T0CONbits.TMR0ON=1;
while(INTCONbits.TMR0IF==0);
T0CONbits.TMR0ON=0;
INTCONbits.TMR0IF=0;
}