PulseIn function is too slow for my Sonar

Hello,

I have sonar HC-SR04 connected to my Ardino using this source code:

#define echoPin 7 // Echo Pin
#define trigPin 8 // Trigger Pin
#define LEDPin 13 // Onboard LED

int maximumRange = 200; // Maximum range needed
int minimumRange = 0; // Minimum range needed
long duration, distance; // Duration used to calculate distance

void setup() {
 Serial.begin (9600);
 pinMode(trigPin, OUTPUT);
 pinMode(echoPin, INPUT);
 pinMode(LEDPin, OUTPUT); // Use LED indicator (if required)
}

void loop() {
/* The following trigPin/echoPin cycle is used to determine the
 distance of the nearest object by bouncing soundwaves off of it. */ 
 digitalWrite(trigPin, LOW); 
 delayMicroseconds(2); 

 digitalWrite(trigPin, HIGH);
 delayMicroseconds(10); 
 
 digitalWrite(trigPin, LOW);
 duration = pulseIn(echoPin, HIGH);
 
 //Calculate the distance (in cm) based on the speed of sound.
 distance = duration/58.2;
 
 if (distance >= maximumRange || distance <= minimumRange){
 /* Send a negative number to computer and Turn LED ON 
 to indicate "out of range" */
 Serial.println("-1");
 digitalWrite(LEDPin, HIGH); 
 }
 else {
 /* Send the distance to the computer using Serial protocol, and
 turn LED OFF to indicate successful reading. */
 Serial.println(distance);
 digitalWrite(LEDPin, LOW); 
 }
 
 //Delay 50ms before next reading.
 delay(50);
}

Well, until pulseIn() finish it takes few miliseconds. This sonar have maximum range about 4m so it takes: 4m / 300 * 2 = 0.026s!! It's too much waiting becouse I'm using MPU6050 too and my main loop need about 130Hz frequency. (it is for quadcopter)

How can it be solved pls?

(it is very stupid sonar, don't know why ECHO is not working simple as analog output)

You could try using two interrupts or an interrupt and a count.

volatile unsigned long signal = -1;
volatile unsigned long time1 = -1;
volatile unsigned long time2 = -1;

void setup()
{ 
  Serial.begin(9600);
  
    //attachInterrupt(0, timing, CHANGE);
    attachInterrupt(0, timing1, RISING);
    attachInterrupt(1, timing2, FALLING);
  
}

void timing1()
{
 time1 = micros(); 
 
}

void timing2()
{
 time2 = micros();
  signal = (time2 - time1) ;
}

I made a pulseIn custom made using millis(), it's not difficult.

jurass17:
How can it be solved pls?

(it is very stupid sonar, don't know why ECHO is not working simple as analog output)

you could try increasing the speed of sound :blush:

you could try increasing the speed of sound

Would I do that using #define or const int? 8)

Have you looked at using the NewPing library?

PaulS:

you could try increasing the speed of sound

Would I do that using #define or const int? 8)

I was wondering one day what's the difference.