With only three wires and a few lines of code, we have built a first version of
a digital metering rule. At the moment, it outputs only centimeter distances
in whole numbers, but we’ll increase its accuracy tremendously in the next
section by changing our software and adding more hardware.
Increasing Precision Using Floating-Point Numbers
According to the specification, the PING))) sensor is accurate for objects that
are between 2 centimeters and 3 meters away. (By the way, the reason for
this is the length of the pulse that is generated. Its minimum length is 115
microseconds, and the maximum length is 18.5 milliseconds.) With our current
approach, we don’t fully benefit from its precision because all calculations
are performed using integer values. We can only measure distances with an
accuracy of a centimeter. To enter the millimeter range, we have to use
floating-point numbers.
Normally it’s a good idea to use integer operations, because compared to
regular computers the Arduino’s memory and CPU capacities are severely
limited and calculations containing floating-point numbers are often expensive.
But sometimes it’s useful to enjoy the luxury of highly accurate floating-point
numbers, and the Arduino supports them well. We’ll use them to improve
our project now:
InputDevices/Ultrasonic/Float/Float.ino
const unsigned int PING_SENSOR_IO_PIN = 7;
Line 1
const unsigned int BAUD_RATE = 9600;
-
const float MICROSECONDS_PER_CM = 29.155;
-
const float MOUNTING_GAP = 0.2;
-
const float SENSOR_OFFSET = MOUNTING_GAP * MICROSECONDS_PER_CM * 2;
5
-
void setup() {
-
Serial.begin(BAUD_RATE);
-
}
-
void loop() {
10
const unsigned long duration = measure_distance();
-
if (duration == 0)
-
Serial.println("Warning: We did not get a pulse from sensor.");
-
else
-
output_distance(duration);
15
}
-
-
const float microseconds_to_cm(const unsigned long microseconds) {
-
const float net_distance = max(0, microseconds - SENSOR_OFFSET);
-
return net_distance / MICROSECONDS_PER_CM / 2;
20
}
-
-
-
Chapter 5. Sensing the World Around Us • 84
report erratum • discuss
www.it-ebooks.info