Accessing the IR sensor from the Arduino IDE

Now, bring up the Arduino IDE. Here is a simple sketch that provides access to the sensor and returns the distance to the object via the serial link:

Accessing the IR sensor from the Arduino IDE

The sketch is quite simple. The three global variables at the top set the input pin to A3 and provide a storage location for the input value and distance. The setup() function simply sets the serial port baud rate to 9600 and prints out a single line to the serial port.

In the loop() function, you first get the value from the A3 input port. The next step is to convert it to a distance based on the voltage. To do this, you need to use the voltage to distance chart for the device; in this case, it is similar to the following diagram:

Accessing the IR sensor from the Arduino IDE

There are two parts to the curve. The first is the distance up to about 15 centimeters and then the distance from 15 centimeters to 150 centimeters. This simple example ignores distances closer than 15 centimeters, and models the distance from 15 centimeters and out as a decaying exponential with the following form:

Accessing the IR sensor from the Arduino IDE

Thanks to teaching.ericforman.com/how-to-make-a-sharp-ir-sensor-linear/, the values that work quite well for a cm conversion in distance are 30431 for the constant and -1.169 as the exponential for this curve.

If you open the Serial Monitor tab and place an object in front of the sensor, you'll see the readings for the distance to the object, as shown in the following screenshot:

Accessing the IR sensor from the Arduino IDE

By the way, when you place the object closer than 15 cm, you should begin to see distances that seem much larger than should be indicated. This is due to the voltage to distance curve at these much shorter distances. If you truly need very short distances, you'll need a much more complex calculation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.67.22