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

Nice job Tim
It took some time to find points for improvement :wink:

All functions now return 0 only when there's no ping echo

That calls for a

#define  NOECHO  0

makes the code more readable

(style remark)
adding a few blank lines in your code might improve readability

Comparing against 0 is faster and makes code a few bytes smaller

// Alternate, uses loop counting to time ping echo.
unsigned int NewPing::ping() 
{
	unsigned long maxLoops = microsecondsToClockCycles(_maxEchoTime + MAX_SENSOR_DELAY) / CLOCK_CYCLES;
	unsigned long maxLoops2 = microsecondsToClockCycles(_maxEchoTime) / CLOCK_CYCLES;

	// Use port registers to trigger a ping.
	*_triggerOutput &= ~_triggerBit;
	delayMicroseconds(2);
	*_triggerOutput |= _triggerBit;
	delayMicroseconds(10);
	*_triggerOutput &= ~_triggerBit;

	// Set a timeout and wait for the echo pin to clear 
	while (*_echoInput & _echoBit)
		if (maxLoops-- == 0) return NOECHO;

        // Wait for the ping to start.
	while (!(*_echoInput & _echoBit))
		if (maxLoops-- == 0) return NOECHO;

	// Ping started, wait for the ping echo to return.
	while (*_echoInput & _echoBit)
		if (maxLoops2-- == 0) return NOECHO;

	// Calculate ping time, 16 = clock cycles of routine overhead.
	return clockCyclesToMicroseconds(numloops * CLOCK_CYCLES + 16); 
}

Still don't like this one...

#define NewPingConvert(echoTime, conversionFactor) (max(echoTime / conversionFactor, (echoTime ? 1 : 0)))

can be improved by (1) adding rounding and (2) working in millimeters as proposed before.

The granularity of measurement = 4 micros(), in 4 micros sound travels approx 1.35 millimeter, or about 1/7 of a centimeter. that's almost 3 bits of precision, assuming the last 2 are noise your lib should be able to measure 0.5cm == 5mm steps (1/10th inch) without problems.