Function executes to slow

Hi everybody,

I’m doing a project for which i need the lowest value of the measurements of 3 HC-SR04 sensors. I came up with this code:

int readSensors (){
  // This function returns the smallest of the sensor outputs
  int sensArray[3];
  int dist;
  for (int i = 0; i < 3; i++ ) {
    sensArray[i] = round(hc.dist(i));  // hc.dist(i) returns the distance measured by the i'th sensor
  dist = min(sensArray[0], min(sensArray[1], sensArray[2]));
  return dist;

When I use this fuction, the program slows down a lot. Is there anyway I can rewrite this function to make it excecute faster?

Thanks in advance for any anwsers.

You need to post a complete code. Not much to tell from this snippet.

Is hc.dist a blocking function using pulseIn? If so that’s your problem. Your function is sitting and waiting for an echo. The only way you make that faster is to increase the speed of sound.

Or rewrite with non-blocking code.

You can reduce the time that the sketch waits for an echo by setting the timeout parameter in pulseIn(). The default timeout is around 1 second. You can shorten that considerably depending on your use.

The non-blocking way is the best way though. I believe that the Ping library has non-blocking ranging functions.

I believe that the Ping library has non-blocking ranging functions.

I know NewPing does.

We were recently playing with using the timer 1 interrupt capture to get non-blocking ranging over in the sensor board. Here. I kept working after the thread ends, and I have something that is nominally better, but not by much and I don't have the code with me. I will post it on that thread later.


Thank you for your responses.

After trying to use the NewPing library and many other things, I discovered the problem. When placing 2 sensors back to back, the library I was using generated unexected outputs, which slowed the function down. I have now placed the sensors beside eachother and now the program is working excelently.

Thanks again for the responses and my apolagies for wasting your time