#define trigPin 12
#define echoPin 11
#define MAX_DISTANCE 200
// define the timeOut according the maximum range. time out= 2*MAX_DISTANCE /100 /340 *1000000 = MAX_DISTANCE*58.8
float timeOut = MAX_DISTANCE * 60;
int soundVelocity = 340;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
delay(100);
Serial.print("Ping: ");
Serial.print(getSonar());
Serial.println("cm");
}
float getSonar() {
unsigned long pingTime;
float distance;
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pingTime = pulseIn(echoPin, HIGH, timeOut);
distance = (float)pingTime * soundVelocity / 2 / 10000;
return distance;
}
Comments
Please log in or sign up to comment.