Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Table of Contents
1
Overview/Objective .............................................................................................................................. 2
1.1
Mission Checklist................................................................................................................................... 3
How it Works......................................................................................................................................... 4
4.1
4.2
4.2.1
4.2.2
Setup ............................................................................................................................................. 9
5.1.1
Parts .......................................................................................................................................... 9
5.1.2
5.1.4
5.2
5.2.1
5.2.2
MATLAB ............................................................................................................................... 11
5.2.3
5.2.4
5.3
5.3.1
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
5.4.1
5.5
5.6
End-to-End Test........................................................................................................................... 21
1|EE444
6.1
6.2
9.2
10
9.2.1
9.2.2
References ...................................................................................................................................... 29
Appendix A
Appendix B
IR Detection Cards............................................................................................................... 30
Appendix C
Appendix D
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
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
3. Most of the material in this document can be found in Chapter 23 Analog-to-Digital Converter
of the ATmega328P Datasheet.
Mission Checklist
3|EE444
How it Works
4.1
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
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
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
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
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.
Please Do Not Forget to document your experimental setup and results in your lab notebooks
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)
9|EE444
Example Resistance
Shown (see write-up)
5.2
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
Figure 5.1
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
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
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
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
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
18 | E E 4 4 4
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
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.
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
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
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
This shows the sensitivity (slope) of the Long Range IR vs. the Short Range IR.
22 | E E 4 4 4
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.
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
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
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()
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);
}
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
Appendix A
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
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
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
31 | E E 4 4 4
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