/** HCSR04.h -- Arduino library to use HC-SR04 ultraSonic
 **	distance sensor using timer2 and D2 or D3 interrupts.
 ** munged up by: schip Oct 2018
 **
 **  As implemented this uses:
 **		timer 2 at a prescale of /1024 for a 64uS resolution
 **		any digital pin as the trigger output
 **		either D2 or D3 for the ping input
 **		note: tested with D2 as trigger and D3 as ping....
 **	  Resulting in a count range of about
 **		12 at minimum and clamped at 512 at maximum, for no ping return
 **		 seems to be about 2cm to 200cm (12-180cnt) good returns
 **		 multiply counts by 1.1 to get approx cm
 **		if something goes wrong a negative value is returned
 **		 When no ping is returned this takes about 200mS to cycle.
 */

#ifndef HCSR04_H
#define HCSR04_H

/** possible error values from getDistance() **/
#define HCSR04NODATA 0x0000	// nothing found
#define HCSR04FAILED 0x8000	// failed

//#define DEBUG	// set to do a bit of debug tracing

#define LEDPIN 13	// the flashy LED for debug
#ifdef DEBUG
extern uint8_t _uSflags;
#endif

class HCSR04
{
public:
	/** default constructor **/
	HCSR04();	
	/** initialize the HC-SR04 sensor pins and timer interrupts
	 **  leaves all the interrupt disabled
	 **   use SR04.startPing() to start a sample cycle **/
	void init( uint8_t trigpin, uint8_t pingpin );

	/** Start a sensor ping cycle
	 **  turns on TRIGPIN and enables interrupts
	 ** Presumes that SR04init() initTimer2() have already been called.  **/
	void startPing(void);

	/** return true if there is a new distance value available
	 **  will clear itself, so a second call will return false...  **/
	bool available(void);

	/** return the last distance value from the sensor
	 **  if it's 0x8000 we didn't get anything...  **/
	int16_t getDistance(void);

private:
	// initialize the trigger out and ping in pins and interrupts
	//  leaves the interrupt disabled
	void pingInit( uint8_t trigpin,  uint8_t pingpin);

	// init Timer2 to "normal" mode and set compare match value
	//  leaves timer NOT running and interrupts disabled
	void initTimer2( uint8_t compare );

}; // end of class HCSR04

#endif // HCSR04_H
