i want to run two HC-SR04 on one PIC16F877A and send the value mesured by the two ultrasonic to serial port.
this is my code using PIC C Compiler :
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)
#define e1 PIN_B6
#define t1 pin_B7
#define e2 pin_B4
#define t2 pin_B5
int a;
int distanse(int,int);
void main()
{
while(1){
int u1,u2;
u1=distanse(e1,t1);u2=distanse(e2,t2);
printf("%3u", u1);
printf("%3u", u2);
delay_ms(1000);
}
}
int distanse(int e,int t){
long long counter=0;
output_bit(t,1);delay_us(10);output_bit(t,0);
a=input(e);
while(a==0){a=input(e);}
while(a==1){counter=counter+1;a=input(e);}
return counter/3.333333;
}
but computer received random values ! what is the problem ?
per the documentation for the device,
"You only need to supply a short 10uS pulse to the trigger input to start the ranging, an d then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo. The Echo is a distance object that is pulse width and the range i n proportion .You can calculate the range through the time interval betwe en sending trigger signal and receiving echo signal. Formula: uS / 58 = centimete rs or uS / 148 =inch; or: the range = high level time * velocity (340M/S) / 2; we suggest to use over 60ms measurement cycle, in order to prevent trigger sign al to the echo signal"
the measurement is NOT how long the signal stays high, but rather the time BETWEEN the end of the 'start' pulse and the beginning of the input signal being high.
Therefore, the code is measuring the wrong interval.
It should be measuring the 'low' interval, not the 'high' interval.
The documentation is available at: http://www.micropik.com/PDF/HCSR04.pdf
Of note, since your running two of the devices, the time between measurements (of any device), per the documentation, needs to be over 60msec.
I'm not seeing the needed time interval between triggering the different devices.
I would suggest using the delay_us() function for time interval measurement rather than a free running while loop