Would you please explain how did you get this formula:
distance = ((time*340)/2)*100 //in cm
Allen
#include <pic.h>
__CONFIG (0x3732);
#define trigger RC2
#define echo RC3
#define _XTAL_FREQ 20000000
#define MHZ *1000L
#define KHZ *1
#define DelayUs(x) { unsigned char _dcnt; \
_dcnt = (((x)*(20MHZ))/(24MHZ))|1; \
while(--_dcnt != 0) \
continue; \
_dcnt = (((x)* (20MHZ))/(24MHZ))|1; \
while(--_dcnt != 0) \
continue; }
void DelayMs(unsigned char y);
void main (void)
{
unsigned char i;
unsigned int time;
unsigned int distance;
TRISC = 0b00001000;
PORTC = 0b00000000;
TRISD = 0b00000000;
PORTD = 0b00000000;
T1CON = 0b00000000;
TMR1H = 0;
TMR1L = 0;
while(1)
{
for (i=0;i<8;i++)
{ TMR1H=0;
TMR1L=0;
trigger = 0;
DelayUs(2);
trigger = 1;
DelayUs(10);
trigger = 0;
while (echo==1);
TMR1ON = 1;
while (echo==0);
TMR1ON = 0;
time = TMR1H;
time = time<<8;
time = time|TMR1L;
DelayMs (10);
}
time = time/5;
distance = time/58;
if(distance<15){
PORTD = 0b10000000;
}
}
}
void DelayMs(unsigned char y)
{
unsigned char i;
do {
i = 4;
do {
DelayUs(250);
} while(--i);
} while(--y);
}
long microsecondsToCentimeters(long microseconds)
{
// The speed of sound is 340 m/s or 29 microseconds per centimeter.
// The ping travels out and back, so to find the distance of the
// object we take half of the distance travelled.
return microseconds / 29 / 2;
}
time = time/5;
distance = time/58;
#include <pic.h>
__CONFIG (0x3732);
#define trigger RC2
#define echo RC3
#define _XTAL_FREQ 20000000
void main ()
{
unsigned char i;
unsigned int time;
unsigned int distance;
TRISC = 0b00001000;
PORTC = 0b00000000;
TRISD = 0b00000000;
T1CON = 0b00000000; //prescalar of 1:1
TMR1H = 0;
TMR1L = 0;
while(1)
{
for(i=0;i<8;i++)
{
TMR1H=0;
TMR1L=0;
trigger = 0;
__delay_us(2);
trigger = 1;
__delay_us(10);
trigger = 0;
while(echo==1);
TMR1ON = 1;
while(echo==0);
TMR1ON = 0;
time = TMR1H;
time = time<<8;
time = time|TMR1L;
__delay_ms (10);
}
distance = time/58;
distance = time/5; //to get time of 1us
if(distance<15){
PORTD = 0b10000000; //to enable LED on port D7
}
}
}
Users browsing this forum: No registered users and 14 guests