I'm using a basic trig/echo Ultrasonic Sensor with an Arduino Uno. I get accurate readings until I cover the sensor at which point I receive very large numbers. Why is this?
Program
int trigPin = 8;
int echoPin = 9;
float pingTime;
float targetDistance;
const float speedOfSound = 776.5; // mph
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
}
void loop() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2000);
digitalWrite(trigPin, HIGH);
delayMicroseconds(15);
digitalWrite(trigPin, LOW);
delayMicroseconds(10);
pingTime = pulseIn(echoPin, HIGH);
pingTime /= 1000000; // microseconds to seconds
pingTime /= 3600; // hours
targetDistance = speedOfSound * pingTime; // miles
targetDistance /= 2; // to from target (averaging distance)
targetDistance *= 63360; // miles to inches
Serial.print("distance: ");
Serial.print(targetDistance);
Serial.println("");
delay(100);
}
Example Output
I moved my hand from 10" away until I cover the sensor
10.20 distance: // my hand is 10" away from the sensor
10.01 distance:
9.51 distance:
8.71 distance:
7.85 distance:
6.90 distance:
5.20 distance:
4.76 distance:
3.44 distance:
2.97 distance:
1.65 distance:
1211.92 distance: // my hand is now pressed up against the sensor
1225.39 distance:
1197.16 distance:
1207.43 distance:
1212.66 distance:
1204.60 distance:
EDIT
I changed the amounts from inches
to milimeters
to get a more precise reading. I held the sensor ~100mm from a granite counter-top and quickly lowered it until the tabletop covered the front of the sensor.
distance: 103.27 // 100mm from tabletop
distance: 96.50
distance: 79.84
distance: 76.72
distance: 62.66
distance: 65.78
distance: 54.85
distance: 47.04
distance: 44.95
distance: 38.71
distance: 28.81
distance: 25.69
distance: 27.08
distance: 25.17
distance: 27.77
distance: 22.04 // sensor continues toward table but values start to increase when they would logically decrease ??
distance: 23.95
distance: 26.73
distance: 28.81
distance: 46.52
distance: 2292.85 // sensor is now flush against tabletop
distance: 2579.59
distance: 2608.75
distance: 2595.56
distance: 2591.57
distance: 2583.75
distance: 2569.87
distance: 2570.91
distance: 2600.07
distance: 30579.64 // extreme high & low values with sensor is same place against tabletop
distance: 37.66
distance: 30444.43
distance: 37.66
distance: 30674.23
distance: 38.71