# define echoPin 2 // The number of the digital pin connected to the echo input
# define trigPin 3 // The number of the digital pin connected to the trigger output
int maximumRange = 30; // The max distance observed from the sensor
int minimumRange = 0;
long duration, distance; //duration used to calculate distance
void setup()
{
Serial.begin(57600);
echoSetup();
}
// just call a test function loop to see if the echo thing works
void loop()
{
echoLoop();
}
void echoSetup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
int getEcho()
{
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = duration / 58.2;
/*
// error handling removed here !!!
; setup
# define LEDPin 13 // This enables the LED feedback for testing
pinMode(LEDPin, OUTPUT); //board LED for testing
; here in getEcho
if (distance >= maximumRange || distance <= minimumRange) {
Serial.println("-1"); //if nothing observed ouput -1
digitalWrite(LEDPin, HIGH); // LED will be on
} else {
Serial.println(distance); // prints the distance in CM
digitalWrite(LEDPin, LOW); // LED will be off if object detected
}
*/
return distance;
}
void echoLoop() {
Serial.println(getEcho());
delay(100); // good practice not to overload the serial port
}