# read from Ultrasonic HC-SR04

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 the computer received random values ! what is the problem ?

• For debugging, add a printf of counter in your so-called "distanse" function. Maybe the long long counter result isn't fitting into an integer – James Waldby - jwpat7 Apr 27 '15 at 18:43

## 1 Answer

Ultrasonic sensors work by emitting a set of pulses and reading the return signal (here is a better overview), this causes problems when you have more than one as they cannot distinguish between their own sensor and the other. I would suggest putting a 500ms delay after each reading to avoid as much interference as possible while you keep the same read rate.