NewPing Library: HC-SR04, SRF05, SRF06, DYP-ME007, Parallax PING))) - v1.7

fairorgan got me to thinking about exactly how much processing time is spent using the ping_timer method. Which also helps to understand what else your sketch could be doing in the remaining time. So, I wrote a sketch to tests this. The sketch runs for 30 seconds and logs how much time is spent both initiating the ping and checking for the return echo. It's not perfect, as there's some overhead in doing these calculations making these estimates a little on the high side. Anyway, here's the results with pings happening every 29ms.

5cm pings = <1% load
20cm pings = 2% load
70cm pings = 7% load
125cm pings = 12% load
200cm pings = 19% load
500cm pings = 45% load

When reducing the maximum sensor distance value when calling the NewPing constructor, you can greatly reduce the maximum ping_timer load. For example, if you leave it at the default of 500cm, using ping_timer every 29ms will use up to 45% processor load. However, lowering the max distance to 200cm means the maximum load can be only 19%, or lowering it to 50cm makes the max load only 5%. So, setting a maximum distance to the longest distance you need will greatly free up the ATmega to do other parts of your sketch.

The ping frequency also effects the processor load. The above numbers were all done at a 29ms ping rate. However, if the ping rate is every 100ms, the load is drastically reduced to only 5.5% (down from 19%). 200cm maximum distance and pinging every 50ms uses a maximum of 11% processor load.

So, when creating an interrupt driven sketch and using NewPing, setting the maximum sensor distance and ping rate to what you really need for your project will greatly effect how much processing time you have available to do other parts of your sketch. Doing a maximum ping rate of 29ms and leaving the default maximum distance at 500cm will use almost half of the ATmega processing time (45%). If your project really only needs to sense out to 200cm and pinging once every 100ms is all the faster you really need, you've lowered the processing time down to only 5.5% (almost 1/10th the load).

Keep in mind that these are maximum load amounts. If the a ping echo is sensed at a shorter distance, the load can be greatly reduced. For example, the 45% load for a max distance of 500cm at a 29ms ping rate is only if there's a NO_ECHO (zero value). If under the same settings there's a constant ping echo at 10cm, the load is only 1%. So, these are truly worse case numbers. But, to avoid your sketch to be sluggish at times, you should consider the worst case scenario.

Tim