Sei sulla pagina 1di 32

Lab 3 IR Ranger Lab

Table of Contents
1

Overview/Objective .............................................................................................................................. 2
1.1

Uno and Nano Lab Variations ....................................................................................................... 2

Reference Material ............................................................................................................................... 3

Mission Checklist................................................................................................................................... 3

How it Works......................................................................................................................................... 4

4.1

The Sharp Family of IR Sensors ..................................................................................................... 4

4.2

Analog to Digital Converter........................................................................................................... 7

4.2.1

Converting between a Voltage and a Digital Number .......................................................... 7

4.2.2

Sample Frequency ................................................................................................................. 7

Lab Experiments .................................................................................................................................... 8


5.1

Setup ............................................................................................................................................. 9

5.1.1

Parts .......................................................................................................................................... 9

5.1.2

Wire the Circuit ..................................................................................................................... 9

5.1.4

Setup the Test Fixture ......................................................................................................... 10

5.2

Use MATLAB to Characterize the IR sensor ................................................................................ 10

5.2.1

Software Support Libraries ................................................................................................. 10

5.2.2

MATLAB ............................................................................................................................... 11

5.2.3

Sample Dataset ................................................................................................................... 12

5.2.4

Lab Experiment ................................................................................................................... 13

5.3

Calibrate IR sensors ..................................................................................................................... 13

5.3.1

Using MATLAB to Create the IR Data Set (Matlab Path) ..................................................... 14

5.3.2

Using the Arduino IDE to Create the IR Data Set (Arduino Path)........................................ 17

5.3.3 Plot the Long and Mid-Range Data Sets (MATLAB and Arduino Paths)..................................... 17
5.4

Create Linearized Graph ............................................................................................................. 18

5.4.1

Curve Fitting Method - Linearization .................................................................................. 18

5.5

Make ranges.h File for Mission Software .............................................................................. 20

5.6

End-to-End Test........................................................................................................................... 21

Uno and Nano Lab Variations ............................................................................................................. 21

1|EE444

6.1

Wire Master Reader/Slave Sender (Nano Only) ......................................................................... 21

6.2

Plot Sensitivity (Uno Only) .......................................................................................................... 21

The Mission ......................................................................................................................................... 23

Lab Report and Mission Demonstration ............................................................................................. 23

Lab Software ....................................................................................................................................... 24


9.1

range = pgm_read_word(&range_data[dn]) .............................................................................. 26

9.2

Utility Functions .......................................................................................................................... 27

10

9.2.1

Function getRange() ............................................................................................................ 27

9.2.2

Function readADC() ............................................................................................................. 28

References ...................................................................................................................................... 29

Appendix A

Alternative Curve Fitting Method ....................................................................................... 29

Appendix B

IR Detection Cards............................................................................................................... 30

Appendix C

Minimum and Maximum Range ......................................................................................... 30

Appendix D

3.3v to VAREF Resistor Value .............................................................................................. 31

Appendix E

IR Research .......................................................................................................................... 32

Overview/Objective

In this lab, you will learn how to use an IR sensor to measure the distance between objects and your
rover. By doing this, the rover will ultimately be able to map the terrain surrounding it, equip it with
sufficient knowledge to navigate around possible obstructions, and finally reach the desired plaques of
interest.

1.1

Uno and Nano Lab Variations

Some of you have rovers with only the chassis mounted Uno while others, in addition have Arduino
Nanos on the pan and tilt platform. Please implement the lab using the Arduino connected to the IR
sensors. If you have a Nano you will make the connection to the Uno using a Master/Slave scripts at the
end of the lab. While the rovers with Nanos are implementing the Master/Slave scripts, the Uno only
rovers will be conducting an additional test.

2|EE444

Reference Material

Please watch the following Webinar before you begin the lab.
1. Learning Basic Mechatronics Concepts Using the Arduino Board and MATLAB
http://www.mathworks.com/company/events/webinars/wbnr43537.html
2. Oscilloscope Traces, Capacitors, and Distance Sensor Results by Robot Room

Chapter 13 ADC, DAC, and Sensor Interfacing

3. Most of the material in this document can be found in Chapter 23 Analog-to-Digital Converter
of the ATmega328P Datasheet.

Mission Checklist

Here is your checklist for this lab.


Using the IR Sensors Rover measures the distance to an 8 x 11 inch plaque.
The Rover computes the number of shaft encoder tics needed to travel to the plaque, stopping
20 cm in front of it.
Based on this information, the Rover travels in a straight line using the gyro as the primary
sensor and a closed-loop control algorithm, with the shaft encoder(s) providing distance
information. Your rover should stop 20 cm in front of the plaque.

3|EE444

Rover turns around


Rover travels back to the starting point.
Rover turns around

How it Works

4.1

The Sharp Family of IR Sensors

The Sharp GP2Y0A02YK0F IR sensor consists of an infrared emitting diode and a linear CCD array. When
light travels out of the emitter, it will either bounce off an object or not. If the light doesnt bounce then
you will get 0 V at the output. If the light bounces off an object the light will reach the detector creating
a triangle where the points of the triangle are the emitter, point of reflection, and the detector. After a
little geometry, from the angle formed by the emitter and the collector, the distance to the object is
determined.

Figure 4.1

IR Sensor Theory of Operation

You can visualize this linear CCD array as a line of buckets which collect electrons. The number of
electrons in each bucket is directly proportional to the number of photons arriving at that bucket. These
buckets are then sequentially read with a voltage generated corresponding the bucket containing the
most photons.

Figure 4.2

Linear IR CCD Sensor

The GP2Y0A02YK0F is only one of a family of multi-ranging sensors developed by Sharp. The range
comparison for the Sharp GP2XX family is summarized by the following chart.

4|EE444

Figure 4.3

Sharp IR Rangers

Because the angle is being used to determine the distance, there is a nonlinear relationship between the
distance measured by the sensor and its respective voltage output. This relationship may be
approximated by an exponential function.

5|EE444

Figure 4.4

Input Voltage to ADC vs Distance to Reflective Object

As seen from the graph there is a range below the minimum in this case being 4 cm where the voltage
will drop to a voltage which corresponds to a longer distance meaning the robot will misread the
distance to the object. One way to avoid this problem is to simply put the sensor so that the minimum
range is within the robot's perimeter. You can also programmatically solve the problem, by turning off
the sensor after a critical distance is reached (for example 4 cm).

6|EE444

Figure 4.5

4.2

Using Rover to Solve Minimum Range Problem

Analog to Digital Converter

The IR sensor output is an analog output and the Arduino microcontroller, like all microcontrollers,
works in the digital world. As a result, we must modify the output signal of the IR Sensor in order for the
Arduino to make sense of the data; to do this, we must first convert the signal with an analog-to-digital
(ADC) converter. Luckily, the Arduino already has a built in ADC. The Arduino's built in ADC converts the
analog signal into a 10 bit word (which means it will generate a digital number (DN) between 0-1023).
The unipolar ADC uses a reference voltage for comparison to the input voltage. The Arduino has that
voltage reference set to 5 volts by default. This can be changed through code to either 1.1v or an
externally applied voltage, like the Arduino's provided 3.3v. See the separate Analog-to-Digital
Conversion document for all the details.
4.2.1 Converting between a Voltage and a Digital Number
To convert between a given voltage and the resulting digital number (DN) output by the ADC you need
to know the resolution of the ADC (10 bits) and the voltage reference. With these two variables the
conversion factor is equal to VAREF/2n where n is the number of bits. Looking at the IR sensor we see
that the voltage out peaks at around 3.1 V. That means to maximize our resolution we might want to
use the external voltage reference of 3.3V. This will give us a resolution of 0.00322V which can be
translated to a resolution in terms of distance per bit depending on the sensor used. As noted earlier
this relationship is non-linear.
As discussed in the last paragraph to convert between a voltage and a digital number you simply
multiply or divide by a constant. In other words, a linear relationship exists between voltage and DN.
Consequently, to save computing time you may want to work with DN and not voltage. A good analogy
would be the difference between working in metric or English units. They are both methods of putting a
number to a physical measurement.
4.2.2

Sample Frequency

Matlab
The Arduino AnalogRead() function takes a single sample using polling and has an experimentally
measured conversion time of approximately 0.125 msec. The maximum sample frequency is achieved by
setting the ADC mode of the ATmega328P to free-running. In this operating mode the ADC has a
conversion time of 0.108 msec at a clock frequency of fclk = 16 MHz.
The Sharp datasheet tells us that the output of the linear CCD is updated every 16.5 msec +/- 3.7 msec.
So on average we can capture from 132 to 153 samples per update. Based on this information, it would
appear that using the simple Arduino AnalogRead() function will provide us with more than enough
data (132 samples/update).

7|EE444

Figure 7
Waveform for Sharp GP2D12 IR Sensor
source: Robot Room
The output pin of the Sharp sensor repeatedly shows a 0.33V spike even when the distance to the target
is held steady. As shown in the figure, this spike decays to the final DC value after 1.66 usec. Further, the
magnitude of the spike does not decrease at lower voltage levels that occur when the target is at the far
end of the sensor's specified range. That means the signal-to-noise ratio due to the spike is worse when
the object is farther away. Clearly, these spikes can cause an incorrect reading by the ADC of the
ATmega328P and must be factored into our software algorithms.

Lab Experiments

To accomplish our objectives, the lab consists of the following key experiments.

Use MATLAB to characterize IR sensors


Create linearized graph
Make ranges.h file for mission software
Run the Mission

Please Do Not Forget to document your experimental setup and results in your lab notebooks

A cautionary note from Team iBanana S12


A ridiculous, but serious problem we encountered was that we did not inspect the rover that was given
to us from last semester properly prior to starting the lab experimentation. While attempting to create
the IR data set as required, calling the function a.analogRead always result in the maximum digital
number being reported. Our troubleshooting led us to notice that the pin from the shield that is supposed
to go into Aref of the Arduino was bent outside. Once the pin was properly reset in place, we were finally
ready to start the official data collection. Although the troubleshooting routine appeared to take up

8|EE444

mindless hours of work, we learned that proper inspection of all the tools and equipment prior to actual
usage would have saved us quite a bit of step retracing and aggravation.

5.1

Setup

5.1.1 Parts
For this lab, in addition to parts provided with your Rover, you will need the following item(s)

Tape Measure (inches and cm)


5.1.2 Wire the Circuit
Plug IR to Arduino using your specific IRs datasheet to know which pins are Vcc, Gnd, and Vo.
Vo plugs into one of the Analog in. The Sharp IR sensor data sheet and our own experimental
data (Kevin Nguyen S11) recommend inserting a filter capacitor of 10 micro farad capacitor
between Gnd and Vcc near the detector to stabilize the power supply. Read document
http://www.robotroom.com/DistanceSensor3.html to learn more.
You may also want to add a bypass-capacitor 0.01 microfarad (10 nanofarad) between AREF and
ground. See ADC lecture for more on this subject.
Wire a resistor between the 3.3v output on the Arduino and the AREF input pin. Read about
Voltage Reference (VAREF) in the Analog-to-Digital Conversion document. The voltage drop across
the resistor should be no more than 0.1v at a resistance of no less than 750 ohms. I would
recommend starting with a resistance of 1K ohms and measuring the 3.3 v and AREF voltages.
Make sure that the 3.3v is in fact 3.3v. If it is not make sure your 9v battery is in fact at 9v. The
AREF voltage should now be not less than 3.2v. If it is below 3.2v and you are starting with 3.3v
then calculate the current through the resistor and select a new resistor using ohms law which
drops the voltage by no more than 0.1 volts (AREF = 3.2 v). The resistance value should not be
less than 750 ohms.
Your IR electrical circuit is now complete.
During each test run your Arduino should be powered from a power adapter or a fully
charged/new 9v battery.

9|EE444

Example Resistance
Shown (see write-up)

5.1.4 Setup the Test Fixture


All experimental data should be run in the lab. Record the location (front of lab, back bench) and
lighting conditions (i.e., which banks of lights were on, time of day or night). You will want this
information when you run the mission on the day of the final.
Lab Location ___________ Lighting conditions ___________
Tape to the front (not inside) of the plaque a white sheet of paper.
Prepare the location at which you will be taking measurements (e.g., the front of the classroom).
Put strips of black tape on the floor in increments of 10 cm until you have enough for the
required distance of 250 cm.

5.2

Use MATLAB to Characterize the IR sensor

This section was written by Kevin Nguyen (Gyroneers S11), with some additions by Nic Flenghi
(RangeRover F11).
The next section takes you through the software suite needed to complete this lab. If you have
completed the previous labs, you may skip this section.
5.2.1 Software Support Libraries
If you have previously done a lab using Matlab to interface with the Arduino you already have installed
the arduino.m m-file in Matlab and have an Arduino sketch server program (ino or pde) in your
Arduino library (adio, adioe, adioes, motor_v1, or motor_v2). Any of these Arduino server programs will
work with this lab.
1. If this is the first lab you have worked on that uses Matlab, download the Arduino I/O (adios.ino)
and arduino.m m-file from the lab folder. Both are included in the zipped folder named
arduino_io. As an alternative to using the programs found in the lab folder, you can find these

10 | E E 4 4 4

and other Arduino sketch server programs from the MathWorks website (use the blue
Download All button at the top right).
2. Unzip the arduino_io folder and place the arduino.m script in your Matlab directory and the
adios.ino in your Arduino program library.
To start communicating with the Arduino, the general server file adios.ino needs to be uploaded to the
Arduino using the Arduino IDE.
5.2.2 MATLAB
Within MATLAB, set the directory to the folder containing the arduino.m file.
To initiate the connection to MATLAB with the Arduino, type in the following command:
a = arduino('COM63')

If you happen to be using a Mac, the COM# convention is not used. Instead it will look something like
this. Just check what serial port the arduino IDE uses to find yours (Start Devices and Printers).
a = arduino('/dev/cu.usbserial-A900cePn')

The a variable is arbitrary. You can provide any name that you desire, just make sure to change the
code wherever the analogRead function is called. Below is the code which will generate a digital
waveform and a histogram based on the analog output from the sensor.
% The pin number where the sensor is connected
analogPin = 4;
% The amount of measurements to record
sampleSize = 100;
% Set up an array to hold the digital numbers and time
data = zeros(100,2);
% Grab an initial reading to set the bounds of the graph
initialReading = a.analogRead(analogPin);
upperBounds = initialReading + 30;
lowerBounds = initialReading - 30;
% Start the timer
timer = tic;
for n = 1:sampleSize
data(n,1) = a.analogRead(analogPin);
data(n,2) = toc(timer);
subplot(2,1,1);
plot(data(:,2), data(:,1)), axis([0 (sampleSize*0.05) lowerBounds upperBounds]);
subplot(2,1,2);
hist(data(:,1)), axis([lowerBounds upperBounds 0 sampleSize])
drawnow
end

11 | E E 4 4 4

5.2.3 Sample Dataset


Below is a sample graph that was generated in MATLAB. It shows a sample of 100 measurements at the
minimum and maximum range of long range IR sensor. As you can see, the waveform of the long range
IR sensor is fairly clean at the minimum range with several spikes. Setting an initial reading and rejecting
any values out of a small range will remove these high spikes.

Figure 5.1

Waveform and Histogram of a Long Range IR Sensor at Minimum Range

Here is a view of the waveform at the maximum range. The waveform starts to get fairly noisy
compared to the minimum range graph. The results of the histogram show fairly acceptable output. A
combination of an average algorithm with a threshold to reject values can be used to achieve a precise
output.

12 | E E 4 4 4

Figure 5.2

Waveform and Histogram of a Long Range IR Sensor at Maximum Range

In general, the signal of the long range IR sensor gets noisier as the range increases. This is mainly due
to the nature of infrared proximity sensors. Since these experiments were done in a fairly clean
environment, the capacitor did not have a large effect on the waveforms. However as denoted by the
data sheet, a 10uF capacitor or larger should be used in order to stabilize the power supply. This
capacitor should be wired as close to the sensor head as possible (i.e., on the scan platform). DO NOT
WIRE THE CAPACITOR TO THE SENSOR OUTPUT.
5.2.4 Lab Experiment
Using Matlab, generate a waveform of digital number (DN) as a function of time. Next create a
histogram showing the number of DN values recorded for a given number of samples (i.e., the data set).
Each data set should contain at least 100 measurements.
In your lab report, provide the above plots at the minimum, middle, and maximum range of your IR
sensor. Be sure to discuss your results.

5.3

Calibrate IR sensors

IMPORTANT One of our lab objectives is to model our IR sensor data in order to create a look-up table
to convert a digital number into a distance in centimeters. Following are two approaches to create the

13 | E E 4 4 4

original data set used in model development. Section 5.3.1 uses MATLAB while the Section 5.3.2 uses
the Arduino IDE. Which software application path you follow (MATLAB or Arduino) is left up to you.
5.3.1 Using MATLAB to Create the IR Data Set (Matlab Path)
In this step you will be working with Matlab to create a table of distance vs digital number (DN). As
mentioned in the previous paragraph, our ultimate goal is to use this data to create a polynomial model
of our sensor - so the more distances you test for the more accurate your model. If you are taking your
measurements in English units, please convert to Metric Units in your lab notebook. It would probably
be easier to simply tape off distances in metric.
Record your measurements at different distances into a table using the MATLAB code below. This code
will take 100 samples at each distance (from 10cm to 140cm) and automatically arrange the results into
a table for output. Make sure your rover is at the closest (10 cm) mark, and then run the program. A
plot of the data as it is gathered will pop up, and the end results will display in the command window.
Move the rover 10cm back then click anywhere within the figure to run the loop again. Repeat until all
data points are gathered. (use Ctrl + C to cancel mid experiment).
The commands at the end will produce the maximum, minimum, average, and standard deviation of the
data set (i.e., the Sample Standard Deviation). You may also want to calculate the standard deviation for
each data set taking into account all your experimental results (i.e., the Population Standard Deviation).
Before you begin verify that ...
Power provided from external source (not USB) and 5v to Adafruit motor shield is in fact 5v
Aref is 3.3v
ANALOG IN pin your sensor is wired to and the pin designated in the code are the same.
% The pin number where the sensor is connected
analogPin = 4;
% Use external 3.3v reference source wired to AREF
a.analogReference(external);
% throw out first value after AREF change
a.analogRead(analogPin);
% setup a table for our output
results = zeros(14,5);
% label the distances in the left-most column (10cm to 140cm)
x = 10:10:140;
results(:,1) = x';
for i=1:14 % index for the 14 data entries, 10cm to 140cm at 10cm increments
% The amount of measurements to record
sampleSize = 100;
% Set up an array to hold the digital numbers and time
data = zeros(100,2);
% Grab an initial reading to set the bounds of the graph
initialReading = a.analogRead(analogPin);
upperBounds = initialReading + 30;

14 | E E 4 4 4

lowerBounds = initialReading - 30;


% Start the timer
timer = tic;
for n = 1:sampleSize
data(n,1) = a.analogRead(analogPin);
data(n,2) = toc(timer);
subplot(2,1,1);
plot(data(:,2), data(:,1)),axis([0 (sampleSize*0.05) lowerBounds upperBounds]);
subplot(2,1,2);
hist(data(:,1)), axis([lowerBounds upperBounds 0 sampleSize])
drawnow
end
% results are arranged in a table from left to right. Output will be seen
% in Command Window.
% Find the maximum of the data set
results(i,2) = max(data(:,1));
% Find the minimum of the data set
results(i,3) = min(data(:,1));
% Compute the average
results(i,4) = mean2(data(:,1));
% Compute the standard deviation
results(i,5) = std(data(:,1))
% pause the program until a key or button press is detected in the Figure
% Window. Click on the figure or press any key when you're ready to take
% the next sample.
w = waitforbuttonpress;
end

Before you start the lab slowly move your sensor back and forth and watch for the highest DN value
(since it drops once you pass the minimum distance). For our example we will assume at a minimum
distance of 10 cm a mean value of 869 and the maximum observed value of 879. As you conduct the lab
you will discover that invalid data points introduced by noise will be well outside this range. For our
example 880 to 1023. The distance at which the maximum value is recorded and the value itself will
change from sensor-to-sensor, so you will need to experimentally find both for your IR sensor. For
example, your minimum range may be 15 cm. Insert your experimentally measured cut-off value in the
box below.
% Change the 879 to a number which will delete the values higher than the max number
data(data > 879) = [];

The histogram (previous section) is used to provide a view of the characteristics of the data set.
Here is a representative data set for a long range IR sensor.
Distance (cm)
Maximum
Minimum

Average

30
60
90

1023
1023
916.4615

15 | E E 4 4 4

1023
1023
925

1023
1023
915

Standard
Deviation
0.0000
0.0000
1.9681

100
120
150
180
210
240
270
300
330
360
390
400
420
450
480
500
510
550

876
780
699
654
612
585
553
538
520
500
494
474
475
454
423
424
416
419

869
775
688
641
602
568
543
530
510
490
480
461
461
433
407
401
401
400

870.3478
775.9885
690.6092
641.9231
603.0515
571.1868
548.6374
534.5056
516.1724
496.7529
484.1429
464.7174
466.6064
437.6630
413.9474
408.4211
408.6238
406.3404

0.9993
0.9941
2.7549
1.5146
1.5503
3.6145
2.9684
3.2197
2.3586
2.1039
3.5232
3.4683
3.0943
4.2511
4.2260
3.8387
2.9263
3.5304

Minimum

Average

Standard
Deviation

Record your medium range IR data here.


Distance (cm)

Maximum

10
20
30
40
50
60
70
80
90
100
110
120
130
140
5.3.1.2 Using MATLAB to Create the IR Data Set for the Long Range IR Sensor
Repeat the steps in Section 6.3.1 with the following changes made to the medium range code (locations
are shown in yellow in the code). These changes were correct for one team but may not correctly
represent your rovers configuration, so be ready to adapt if needed.
analogPin = 3
results = zeros(17,5);
x = 100:10:260;

16 | E E 4 4 4

for i=1:17

Before you begin verify that ...


Power provided from external source (not USB) and 5v to Adafruit motor shield is in fact 5v
Aref is between 3.2v and 3.3v
ANALOG IN pin your sensor is wired to and the pin designated in the code are the same.
5.3.2 Using the Arduino IDE to Create the IR Data Set (Arduino Path)
See Section 9 Software for the Arduino program used to generate the following data.
Long Range IR
100 minimum = 519, maximum = 542, mean = 525.03, sample variance = 24.86, standard variance = 24.74
120 minimum = 468, maximum = 490, mean = 474.17, sample variance = 22.72, standard variance = 22.61
150 minimum = 422, maximum = 451, mean = 428.09, sample variance = 20.07, standard variance = 19.97
180 minimum = 386, maximum = 418, mean = 393.37, sample variance = 25.72, standard variance = 25.59
210 minimum = 364, maximum = 389, mean = 370.89, sample variance = 19.58, standard variance = 19.48
240 minimum = 352, maximum = 381, mean = 359.69, sample variance = 27.91, standard variance = 27.77
270 minimum = 328, maximum = 351, mean = 333.70, sample variance = 17.45, standard variance = 17.37
300 minimum = 316, maximum = 348, mean = 326.99, sample variance = 42.81, standard variance = 42.60
330 minimum = 306, maximum = 329, mean = 315.92, sample variance = 05.23, standard variance = 05.21
360 minimum = 296, maximum = 323, mean = 303.23, sample variance = 24.71, standard variance = 24.59
390 minimum = 288, maximum = 324, mean = 296.77, sample variance = 19.18, standard variance = 19.08
400 minimum = 288, maximum = 313, mean = 293.59, sample variance = 26.67, standard variance = 26.53
420 minimum = 277, maximum = 309, mean = 291.80, sample variance = 52.82, standard variance = 52.56
450 minimum = 288, maximum = 316, mean = 288.85, sample variance = 31.34, standard variance = 29.19
480 minimum = 244, maximum = 303, mean = 286.53, sample variance = 30.50, standard variance = 30.35
500 minimum = 273, maximum = 307, mean = 285.46, sample variance = 27.37, standard variance = 27.24

Rerun the Arduino program to generate the dataset for the Medium Range IR.
5.3.3 Plot the Long and Mid-Range Data Sets (MATLAB and Arduino Paths)
Using Matlab or Excel make a graph overlaying the mid-range and long range IR data as shown here.

17 | E E 4 4 4

5.4

Create Linearized Graph

Begin by reading these articles


1. Linearizing Sharp Ranger Data
2. Sharp Application Note: Distance Measuring Sensors
3. Robot Sensor Interpretation
There are two methods for fitting your data points to an equation. The preferred method is covered
here, with the alternative method provided in Appendix A. Having said that, Appendix A includes tips
and tricks you will need to work with Excel.
5.4.1 Curve Fitting Method - Linearization
The curve fitting method is based on an article by Acroname Robotics and Sharp. This method
recognizes the inverse relationship between voltage and distance exhibited by the Sharp IR family of
sensors. Knowing this relationship exists, we can "linearize" the response of the Sharp sensors.
According to page 10 of the Sharp Device Specification for Distance Measuring Sensor Model
No. GP2D120, a plot of the following interpolated equation is demonstrated:
y1 = 1 / (R + k)

18 | E E 4 4 4

eq. 1 Linearization Function

Where y1 is the output of the linearization function, R is the range-to-target in centimeters (cm),
specifically the distances you took your experimental measurements at (Rangeexp), and k is an
empirically derived constant. The division operation acts as a linearizing function that turns the curve
into a linear plot. As seen in the following figure, the equation produces a very straight line.
IMPORTANT: You will probably need to prune your data at both ends of the data set to remove nonlinearity's outside the range of the sensor. This observation is the key to finding a simple approximation
function for a Sharp IR range finder. If your average error is over 0.1 % I will probably ask if you pruned
your data set.
The empirically derived constant (k) in the linearization function depends on the sensor type and
calibration data parameters. The value k = 0.42, works well for the GP2D120 and the calibration points
in the Sharp document, but may not be suitable for other sensors. For example, the Acroname article
found k = 4 worked well for a GP2D12. This constant is represented as k since it may change. The first
step in getting a good voltage-to-range function is to find a constant k that linearizes your data. The
following plot shows how the GP2Y0A700K response graph shown above can be linearized by defining
the variable k = 0.4.
You are encouraged to try different values for k.
The next step is to find a straight line approximation that relates the voltage to the line function
y2 = m * x + b. To find the slope m and y intercept b, of the straight line approximation, follow the steps
defined in Appendix A Using a Trend/Regression Type of "Linear" in place of "Exponential." At this point I
would recommend you skip to and read Appendix A. The resulting line equation is shown in the last
figure. Notice that I had to set the precision displayed to 19 in order to get enough significant digits for
the next step.
y2 =1/(0.0000194377306288555*x - 0.0009224453797846000)-0.4 eq. 2 Straight Line Approximation
Setting the linearization function y1 (eq. 1) equal to the straight line approximation equation y2 (eq. 2)
and solving for range R we have:
R = (1 / (m * x + b)) - k
where for our example:
k = 0.4
m = 0.0000194377306288555
b = - 0.0009224453797846000
Range (R) is now a calculated value (Rangecalc) versus an experimentally determined value (Rangeexp).
The two are plotted together here to show how nicely our calculated value agrees with our
experimentally measured value. I added the equation using a text box.

19 | E E 4 4 4

For any distance between 100 cm (40 in) and 460 cm, our calculated range is in error no more the 5.26/+3.07 with an average of 0.01% with respect to the experimental measured range.
We will now use this equation to generate a C++ header file called ranges.h which contains a look-up
table of our distance values associated with the digital number. This file will be used in future lab
experiments and for the mission.

5.5

Make ranges.h File for Mission Software

1. Open a new Excel file.


2. Row 1 should be incrementally numbered from 0 to 1023. Number the first cell 0 and then enter
the equation =A1+1 in the next cell (to the right). Copy and Paste cell with the equation until you
have numbered all 0-to-1023 columns in row 1. You can also just number a few cells and dragdrop the right edge of the selection box.
3. Row 2 should contain your conversion equation with its corresponding column in row 1 used as
the input value.
=IF(B1<165,435,IF(B1>555,100,1/(0.0000194377306288555*B1-0.0009224453797846)-0.4))
4. Select and copy Row 2, open a new Excel File, paste "value" into the first row.
5. Save as a comma delimited csv text file. Name it rangedata.h
6. Open rangedata.h in notepad.
7. Add Arduino formatting text.
const int range_length=1024;
const unsigned int range_data[] PROGMEM = {
your comma delimited data goes here
};

8. Move this file into your Arduino or AVR Studio project folder - the one containing the .pde or
cpp file.
Lets take a closer look at that =IF(B1<165,...)expression (third bullet point) and the tabular data plotted
in the figure. In an ideal world DN = 0 would map to a distance of 550 cm and DN = 1024 would map to a
distance of 0 cm. But as you can see from the plot, it does not work like that in the real world. Instead

20 | E E 4 4 4

there is a range over which the numbers are believable - for the data provided this is DN = 165 to 555.
So what do you do in these undefined ranges. we want to keep the output continuous, so below 165 I
simply use the last valid minimum distance of 460 cm and for digital numbers above 555 I use the last
maximum valid distance of 100 cm. Between these ranges (165 <= DN <= 555) I had data I could work
with by applying my equation. This in words is what the long IF(...) expression is doing.

5.6

End-to-End Test

The final product of all your work is the two range data tables created in the last section. Before you use
these tables to compute distances in your mission code it is a good idea to in fact prove that they work.
Using the auto-range version of getRange() found in the Mission Software section of the lab, rerun the
original IR lab experiment, but this time have the Rovers IR sensors tell you the distance to the plaque.
Record in your lab report in tabular form the actual distance, distance returned by getRange(), and
error. For this final test, everyone (Uno and Nano lab variations) should implement the test using the
Uno.

Uno and Nano Lab Variations

If you have a rover with only the chassis mounted Uno please complete section 6.6.2 Plot Sensitivity. If
you have an Arduino Nano implement communications between your Uno and Nano as introduced in
Section 6.6.1 Wire Master Reader/Slave Sender. The word Wire is Arduino speak for the I2C
communication protocol which Atmel calls TWI not sure why everyone has to rename the I2C.

6.1

Wire Master Reader/Slave Sender (Nano Only)

Within the Arduino IDE open the Wire Master Reader and Wire Slave Sender scripts. Adapt the script so
that Uno can request distance (an 8-bit unsigned number) from the Nano.

6.2

Plot Sensitivity (Uno Only)

In this section we want to take the first derivative of our range equation in order to plot the sensitivity
of our two IR sensors as a function of distance. In this way we can determine when it is best to use each
sensor.
Range Equation
R = 1/(mx + b) - k
where:
R = range (cm)
x = analog output DN
Sensitivity Equation
First, we solve the range equation for x.
x = [1/(R + k) - b]/m
Second, using the quotient rule we find the first derivative. We also could have used the chain rule (a
special case of implicit differentiation) because the numerator is a constant.

21 | E E 4 4 4

dx/dR = (- 1/m )[1/(R + k)^2]


Where m is the slope obtained from our linearization graphs and R is the distance in cm.
From here, we obtain the plot of derivative vs. distance which will show us which IR sensor has the
greater slope at a particular distance which is what we are interested in.
The graph below shows the result obtained by Team IRAwesome Spring 12 .

This is the data plot in excel

This shows the sensitivity (slope) of the Long Range IR vs. the Short Range IR.

22 | E E 4 4 4

Interpreting the Data


We can see from the graph above that the long-range IR sensor has the mid-range IR sensor beat at
every distance that we can confidently use the long-range IR sensor. From the data collected, we should
use the mid-range IR sensor until we reach about 50 to 60 cm. After that point, it is always better to use
the long-range IR sensor.
Looking Back
This section was first introduced in the Spring 2012 semester. In retrospect the standard deviation (i.e.,
how noisy is the signal) also plays a part in the decision as to which sensor should be used.

The Mission

Now that you have implemented the software to measure distance (Section 9 Lab Software), it is time
to upgrade your existing Mission Code (previous labs) to incorporate your lab code plus additional code
to meet your new mission objectives as defined in Section 3 Mission Checklist.

Lab Report and Mission Demonstration

Document your experimental results and equation(s). Do not to forget to discuss your results.
Your lab report should cover the following items...

Experimental Setup

What resistor did you use and what was resulting AREF, lighting conditions, location, power source, any
other information need to reproduce your experiment.

Matlab Dataset showing raw data and sample time for one experiment
Input Voltage (y-axis) in DN from ADC vs Distance (x-axis) in cm to White target both medium
and long range data overlaid.
Waveform of Long Range IR showing Digital Number (DN) vs. Time for experiment at minimum,
average, and maximum ranges
Histogram of Long Range IR showing Digital Number (DN) vs. Time for experiment at minimum,
average, and maximum ranges
Waveform of Medium Range IR showing Digital Number (DN) vs. Time for experiment at
minimum, average, and maximum ranges
Histogram of Medium Range IR showing Digital Number (DN) vs. Time for experiment at
minimum, average, and maximum ranges
Matlab or Arduino data set for long range IR sensor taking 200 samples per data set
Matlab or Arduino data set for medium range IR sensor taking 200 samples per data set

Note 2: How I came up with 200 samples: Arduino sample period is 0.125 msec, Sharp read period is
16.5 msec +/- 3.7 msec. We want to sample a 1.5 x 16.5 = 24.75 msec window or 24.75 msec / 0.125
msec/sample = 198 or 200 readings.

23 | E E 4 4 4

Linearization Graph with resulting equation.


Range Graph overlaid on experimental data
Range.h Equation and resulting table.
Make ranges.h file for mission software
End-to-End Test Results

Uno and Nano Lab Variations


Uno
o Sensitivity (y-axis) in DN/cm vs Distance (x-axis) in cm to White target both medium
and long range data overlaid.
o Data Analysis Based on sensitivity graph recommend a cross-over algorithm
Nano
o Code used to communicate between the Uno and Nano
Mission
Demonstrate your rover running the mission as defined in Section 3.

Lab Software

Even with a bypass capacitor on the power lines, the signal output contains several traces of noise as the
distance increases. This is mainly due to the nature of infrared sensors, therefore a software algorithm
is needed in order to improve our data collection. The current simple software solution is to compute
the average using a rapid calculation method. To improve this solution while maintaining simplicity
within the algorithm, we can reject noisy values in the calculation of the average.
byte sensorPin=2;
int n = 200; // number of samples
int x = 0;
void setup()
{
Serial.begin(9600);
analogReference(EXTERNAL);
delay(2000);
}
void loop()
{
statPak();
delay(500);
x = analogRead(sensorPin);
Serial.print("last value = ");
Serial.println(x);
delay(2000);
}
void statPak(){
// declare local variable

24 | E E 4 4 4

// AREF = 3.3v reference source

int minVal;
int maxVal;
int x_i;
float A_0;
float A_1;
float Q_0;
float Q_1;
float s2_n;
float o2_n;
// initialization
minVal = 1024;
// modify based on Matlab characterization of your IR sensor(s)
maxVal = 0;
// modify based on Matlab characterization of your IR sensor(s)
A_0 = 0;
Q_0 = 0;
float threshold = 0;
int sampleReading = 25;
// Take an initial reading to calculate a threshold
for (int i=1; i <= sampleReading; i++)
{
threshold += analogRead(sensorPin);
}
threshold = threshold / (float) sampleReading;
for (int i=1; i <= n; i++)
{
x_i = analogRead(sensorPin);
if (x_i < minVal){
minVal = x_i;
}
if (x_i > maxVal){
maxVal = x_i;
}
// Check if the reading is within the accepted bounds
if (x_i < (threshold+25) && x_i > (threshold-25))
{
// statistic package
// rapid calculation method
// http://en.wikipedia.org/wiki/Standard_deviation
A_1 = A_0 + (x_i - A_0)/i;
Q_1 = Q_0 + (x_i - A_0)*(x_i - A_1);
A_0 = A_1;
Q_0 = Q_1;
}
}
s2_n = Q_1/(n-1);
o2_n = Q_1/n;
Serial.print("minimum = ");
Serial.print(minVal);
Serial.print(", maximum = ");

25 | E E 4 4 4

Serial.print(maxVal);
Serial.print(", mean = ");
Serial.print(A_1);
Serial.print(", sample variance = ");
Serial.print(s2_n);
Serial.print(", standard variance = ");
Serial.println(o2_n);
}

9.1

range = pgm_read_word(&range_data[dn])

The following Arduino program example shows how to translate an input from the 10-bit ADC into a
range using a look-up table located in Flash program memory. The table is originally generated in Excel
and then exported as a comma delimited text file (anybody know how to do this easily). The resulting
program is very fast and very accurate.
/*
* range_ir
*
* 16-bit range
* For Arduino with ATmega368P at 16 MHz.
*
* Converts an input from the 10-bit DAC to a 16-bit range
* The range table has 1024 16-bit (1 K words) entries.
* Table size may be reduced by using pgm_read_word_near(range_data + dn)
* Read http://arduino.cc/en/Reference/PROGMEM for examples
* Table size could also be reduced by pruning data set and qualifying
* input. Both are not considered critical at this time due to 16 K words
* of Flash program memory available on the ATmega328P.
* The index into the range table equals a 10-bit digital number returned
* by the DAC Each entry in the range table gives the corresponding
* distance in centimeters.
*
* By Gary Hill
* March 27, 2010
*/
#include <stdint.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
/*
* The range data needs to be unsigned int
*
* rangedata.h should look like this:
* const int range_length=1024;
*
* const unsigned int range_data[] PROGMEM = {
* 437, 437, ...
* };
*
*/
/* place rangedata.h inside folder with your pde file and restart Arduino IDE */

26 | E E 4 4 4

#include "rangedata.h"
byte sensorPin=4;
volatile uint16_t dn;
word range;
// same as unsigned int
void setup()
{
Serial.begin(9600);
Serial.println("in setup");
analogReference(EXTERNAL); // where Varef is 3.3V
}
void loop()
{
dn = analogRead(sensorPin);
range = pgm_read_word(&range_data[dn]);
Serial.print("range = ");
Serial.println(range);
delay(1000);
}

9.2

Utility Functions

The following utility functions are common to many of the programs you will be writing. The first code
example shows you how to translate your ADC reading into a distance measurement using a look-up
table. The second code example shows how to dynamically switch between your two IR rangers.
9.2.1

Function getRange()

9.2.1.1 Manual Version


If you have your ir sensors are not co-aligned (facing in the same direction) use the manual version of
getRange. Call getRange with argument LONG_RANGE_IR to use the long ir sensor, otherwise the
short/medium range sensor will be assumed. If you do not send getRange an argument it will call
autoRange.
#define SHORT_RANGE_IR 0
#define MEDIUM_RANGE_IR 1
#define LONG_RANGE_IR 2
const int long_range_ir_pin = 4;
const int short_range_ir_pin = 3;
int getRange(){autoRange();}
int getRange(int ir_sensor)
{
int dn;
int range;
if (ir_sensor == LONG_RANGE_IR){
// short range IR sensor is wired to this pin
dn = readADC(long_range_ir_pin);

27 | E E 4 4 4

range = pgm_read_word(&range_data[dn]);
}
else {
// long range IR sensor is wired to this pin
dn = readADC(short_range_ir_pin);
range = pgm_read_word(&short_range_data[dn]);
}
// Serial.println(range);
return (range);
}

9.2.1.2 Automatic Version


If your long and short range sensors are co-aligned, this code will pick the best sensor to use. To use the
automatic mode you will need to find the maximum distance value (minimum DN) in the short/medium
range ir lookup table. You can locate this distance in the equation located in your Excel document used
to create this table. Here is a sample equation. If the DN is less than 100 then Excel simple inserted the
distance 72 cm. This is the last valid computed valid so there is no discontinuity in the table. If the DN is
greater than 800 then Excel inserts the distance 8 cm. For autorange we want to switch to the long
range sensor when the short range sensor is beyond its maximum range (DN < 100, distance > 72 cm)
=IF(B1<100,72,IF(B1>800,8,1/(0.00013815799115642500*B1-0.00467800316767518)-0.4))
int autoRange()
{
// replace with experimentally determined value
const int max_range = 72;
// maximum range of the short range IR is 72 cm
int dn;
int range;
// start with short/medium range ir sensor
dn = readADC(short_range_ir_pin); // single data point
range = pgm_read_word(&short_range_data[dn]);
if (range == max_range){
// switch to long range ir sensor
dn = readADC(long_range_ir_pin);
range = pgm_read_word(&range_data[dn]);
}
// Serial.println(range);
return (range);
}

9.2.2 Function readADC()


Depending on the software using the readADC function you may want to change the number of samples
taken (variable n).
int readADC(int sensorPin){
int n = 200;
// number of ADC samples
int x_i;
// ADC input for sample i
float A_1;
// current i running average
float A_0;
// previous i-1 running average

28 | E E 4 4 4

A_0 = 0;
for (int i=1; i <= n; i++){
x_i = analogRead(sensorPin);
// rapid calculation method http://en.wikipedia.org/wiki/Standard_deviation
A_1 = A_0 + (x_i - A_0)/i ;
A_0 = A_1;
}
// Serial.print(", mean = ");
// Serial.println(A_1);
return (int(A_1));
}

10

References
1
2
3
4
5
6
7
8
9
10

Sharp Application Note


Distance Measuring Sensors
http://www.roboticsconnection.com/multimedia/docs/Sharp_GP2D120_IR_Sensor_Specs.pdf
http://www.roboticsconnection.com/multimedia/docs/Sharp_IR_Sensor_App_Notes.pdf
http://forum.pololu.com/viewtopic.php?f=8&t=799
http://commons.wikimedia.org/wiki/File:CCD_charge_transfer_animation.gif
http://en.wikipedia.org/wiki/Triangulation
http://en.wikipedia.org/wiki/Charge-coupled_device
http://www.ikalogic.com/ir_prox_sensors.php
Visualizing Sensor Data with Arduino and Processing

Appendix A

Alternative Curve Fitting Method

Following is an alternative to the curve fitting method covered in Section 6.1.1 Baseline IR Calibration,
Step 5: Plot DN to Distance Relationship. The method described in the lab is the preferred method.
After you have created your digital number vs distance list in excel you will then create the distance
formula by graphing your DN and distance points. Graph your points using the XY "Scatter with Smooth
Lines and Markers". Add titles using Layout 1. Make sure your Y values are your distance values and X
values are your DN values. After this right click on your scatter plot, verify Layout tab is selected, and
click on the Format Trendline submenu icon. Choose more trendline options. In the "Format Trendline"
pop-up window, select the "Display Equations on chart" check box. Now, try different solutions including
polynomial of order 6 (the higher the order the more fit the line will be). In the pop-up window you can
also change the Line Color, Line Style, and Shadow to improve the appearance of your line. You can
always reopen this pop-up window by left clicking the line and selecting "Format Trendline..."
Sometimes Excel will not give you enough significant figures so you must right click on your displayed
equation and click on Format Trendline Label, click on Number under the category section, and put 30
decimal places to make sure you have all significant figures. (Also unclick Use 1000 separator (,) it will
save you some hassle later)

29 | E E 4 4 4

In Excel we add a trend line and fit the data to an equation...

For any distance between 100 cm (40 in) and 460 cm, our calculated range is in error no more the 3.36/+7.20 with an average of 0.05% with respect to the experimental range.

Appendix B

IR Detection Cards

Sharp IR Range Finder - Beam Width using Banner Engineering Magic Mirror Infrared Detector Here
are some sites for purchasing an IR Detection Card. The first link looks like the only card that could
provide good data. From the apparent size of the active area of this and the other cards, your cell phone
is probably just as good.

http://www.maxmax.com/DetectionCards.asp
http://www.fiberoptics4sale.com/Merchant2/merchant.mvc?Screen=PROD&Product_Code=F1IDC
http://www.web-tronics.com/indetcarif.html

Appendix C

Minimum and Maximum Range

The actual minimum and maximum reliable range of your IR sensor may vary slightly from the
specifications. As mentioned previously, the output voltage from the sensor will actually drop as you
move it closer to the target and pass the minimum range mark. To help get a sense of this, try running
the following MATLAB code while moving the sensor slowly back and forth to find the point where this
peak occurs. Perform this test with the reference voltage set to DEFAULT (5v) and again set to
EXTERNAL (3.3v). Record your minimum range value below.
Minimum Range (cm): _______, Digital Number (aref = 5v) :_______, (aref = 3.3v)_______

30 | E E 4 4 4

Next, see how far back you can move the sensor while maintaining a usable signal. Keep in mind that,
since the response curve flattens out the further you get from the target, the precision will decrease
(even if the signal is relatively noise free). Record your maximum range value below.
Maximum Range (cm)_______, Digital Number (aref = 5v) :_______, (aref = 3.3v)_______

Appendix D

3.3v to VAREF Resistor Value

% ------------------------------------------------------------------------% Get input from user


% ------------------------------------------------------------------------clc
analogPin = input('Enter analog pin number: ');
aref = input('"default" or "external" reference voltage?: ','s');
time = input('Time (in secs) to run the loop: ');
% ------------------------------------------------------------------------% set analog reference to either default (5v) or external (3.3v)
a.analogReference(aref);
% throw out the first value after aref change
a.analogRead(analogPin);
% setup array for data readings
data = zeros(1, 2*time+1);
% initialise counter
n = 0;
% start timer
tic
while toc < time % loop until time is up
n = n+1; % increment counter

31 | E E 4 4 4

% read DN value from Arduino


data(n) = a.analogRead(analogPin);
% ------------------------------------------------------------------------% Update plot and command window with current DN and time remaining
% ------------------------------------------------------------------------clc
figure(1)
set(1,'name',[num2str(round(remaining)),' seconds remaining. Use ctrl + C to
escape.'])
plot(0:1/2:time,data)
axis([0 time 0 1023])
xlabel('Time (sec)')
ylabel('Digital Number')
title(['Digital Number: ', num2str(data(n))])
disp(['Digital Number: ', num2str(data(n))])
elapsed = toc;
remaining = time - elapsed;
disp(' ')
disp([num2str(round(remaining)),' seconds remaining. Use ctrl + C to escape.'])
pause(0.5)
% ------------------------------------------------------------------------end
clc
disp('Done!')

Appendix E

IR Research

In the Research folder you will find a Word file named IR Research Experiments. This file contains a
series of experiments conducted by Thushini Manuweera and Hashini Wedagedara to analyze the
behaviour of the IR sensors (both long range and medium range) under different environmental
conditions and look at methods to eliminate noise. The following quote is from the very last section
entitled Future Work and pretty much sums up what needs to be done.
Observation of the actual signal being returned by the IR sensors and methods for eliminating noise.
When Thushini and Hashini conducted their study we did not have a way to actually see and quantify
the data being returned by the IR sensor. With the Matlab tools documented in this lab we can now
complete the work they began.
Read over the experiments in the research document and select an experiment that you would like to
rerun using Matlab. Please, coordinate with me before starting any experiment.

32 | E E 4 4 4

Potrebbero piacerti anche