//////////////////////////////////////////////////////////////////////////////////////////////////// //Title: HCSR04 //Author: Austin Matthew //Purpose: supply arduino sketch with simple library that includes functionallity for HCSR04 sensor //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef HCSR04_h //defining class header #define HCSR04_h #include "Arduino.h" //importing base arduino library. needed for pinValue and PulseIn //****************************************************************************************************************************************************** //Defining certain parts of the class here. Also giving class name //****************************************************************************************************************************************************** class HCSR04ProxSensor { public: // the public section is for things that can be used by other parts of the program HCSR04ProxSensor(int echoPin,int triggerPin); // defining the constructor and its arguments float readSensor(int range); // placing required methods into class header float getLastValue(); float lastValue; // placing public variables that can be read/written to by more than just one method. float currentValue; private: // placing variables in private such that no other //aspect of the program can change them. also useful if more than one object of the same // kind if constructed. int _echoPin; int _triggerPin; }; #endif //****************************************************************************************************************************************************** //actual workings/definitions of functions stated in header file //****************************************************************************************************************************************************** HCSR04ProxSensor::HCSR04ProxSensor(int echoPin,int triggerPin) //constructor { _echoPin = echoPin; // giving object its own set of pins. _triggerPin = triggerPin; lastValue=0; //last and current values are brought in for comparison function. currentValue=0; } float HCSR04ProxSensor::readSensor(int range) //complete setup of URM including pin modes, and timing { // pinMode(_triggerPin, OUTPUT); pinMode(_triggerPin,LOW); // high/lows for ping generation and reading delayMicroseconds(2); pinMode(_triggerPin,HIGH); delayMicroseconds(2); digitalWrite(_triggerPin, LOW); // pinMode(_triggerPin, INPUT); float duration=pulseIn(_echoPin,HIGH); delay(5); // 1 second delay for more manageable reading duration= duration/29/2; // converting time to distance, and cutting it in half, because math. if(duration > range) { currentValue=range; } else{currentValue=duration;} return currentValue; } float HCSR04ProxSensor::getLastValue() { // i dont know enough words to explain the complexity of this function. god help us all. return lastValue; }