#include "Arduino.h" class Ultrasonic { public: Ultrasonic(int pin); void DistanceMeasure(void); double microsecondsToCentimeters(void); double microsecondsToInches(void); private: int this_pin;//pin number of Arduino that is connected with SIG pin of Ultrasonic Ranger. long duration;// the Pulse time received; }; Ultrasonic::Ultrasonic(int pin) { this_pin = pin; } /*Begin the detection and get the pulse back signal*/ void Ultrasonic::DistanceMeasure(void) { pinMode(this_pin, OUTPUT); digitalWrite(this_pin, LOW); delayMicroseconds(2); digitalWrite(this_pin, HIGH); delayMicroseconds(5); digitalWrite(this_pin,LOW); pinMode(this_pin,INPUT); duration = pulseIn(this_pin,HIGH); } /*The measured distance from the range 0 to 400 Centimeters*/ double Ultrasonic::microsecondsToCentimeters(void) { return duration/29.0/2.0; } /*The measured distance from the range 0 to 157 Inches*/ double Ultrasonic::microsecondsToInches(void) { return duration/74.0/2.0; } Ultrasonic ultrasonic(2); void setup() { Serial.begin(9600); } void loop() { double RangeInInches; double RangeInCentimeters; ultrasonic.DistanceMeasure();// get the current signal time; RangeInInches = ultrasonic.microsecondsToInches();//convert the time to inches; RangeInCentimeters = ultrasonic.microsecondsToCentimeters();//convert the time to centimeters Serial.println("The distance to obstacles in front is: "); Serial.print(RangeInInches);//0~157 inches Serial.println(" inch"); Serial.print(RangeInCentimeters);//0~400cm Serial.println(" cm"); delay(1000); }