#define trigPin 12 // define trig pin
#define echoPin 11 // define echo pin
#define MAX_DISTANCE 500 // define max distance
// define the timeOut according to the maximum range. timeOut= 2*MAX_DISTANCE /100 /340*1000000 = MAX_DISTANCE*58.8
float timeOut = MAX_DISTANCE * 58.8;
int soundVelocity = 340; // speed of sound = 340m/s
void setup() {
// put your setup code here, to run once:
pinMode(trigPin, OUTPUT); // trig pin set to output mode
pinMode(echoPin, INPUT); // echo pin set to input mode
Serial.begin(9600); // baud rate 9600
}
void loop() {
// put your main code here, to run repeatedly:
delay(100); // 20 pings per second (29ms is shortest delay)
Serial.print("Ping: ");
Serial.print(getSonar()); // Send ping, get distance in cm, print result (0 if out of range)
Serial.println("cm");
}
float getSonar(){
unsigned long pingTime;
float distance;
digitalWrite(trigPin, HIGH); // make trigPin output high level to help triger HC_SR04
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pingTime = pulseIn(echoPin, HIGH, timeOut);
// calculate distance
distance = (float)pingTime * soundVelocity / 2 / 10000;
// return distance value
return distance;
}