Datasheet
Light-Sensitive Navigation with Phototransistors • Chapter 6
Robotics with the BOE Shield-Bot • 185
The Arduino Map Function
In the PhototransistorVoltage sketch, we converted measurements from the 0 to 1023 range to
the 0.0 to 4.995 volt range for display. For other applications, you might need to convert the
value to some other range of integers so that your sketch can pass it to another function, maybe
for motor control, or maybe for more analysis.
That's where the Arduino’s
map function comes in handy. It's useful for “mapping” a value in one
range of integers to an equivalent value in some other range. For example, let’s say you want to
map a measurement in the 0 to 1024 range to a range of 1300 to 1700 for servo control. Here is
an example of how you could use the map function to do it:
int adcVal = analogRead(A3);
int newAdcVal = map(adcVal, 0, 1023, 1300, 1700);
In this example, if the value of
adcVal is 512 , the result of the map function for the newAdcVal
call would be 1500 . So, the measurement got mapped from a point about half way through the
0..1023 range to its equivalent point in the 1300...1700 range.
How the Phototransistor Circuit Works
A resistor “resists” the flow of current. Voltage in a circuit with a resistor can be likened to
water pressure. For a given amount of electric current, more voltage (pressure) is lost
across a larger resistor than a smaller resistor that has the same amount of current passing
through it. If you instead keep the resistance constant and vary the current, you can
measure a larger voltage (pressure drop) across the same resistor with more current, or less
voltage with less current.
The Arduino’s analog inputs are invisible to the phototransistor circuit. So, A3 monitors the
circuit but has no effect on it. Take a look at the circuit below. With 5 volts (5 V) at the top
and GND (0 V) at the bottom of the circuit, 5 V of electrical pressure (voltage) makes the
supply of electrons in the BOE Shield-Bot’s batteries want to flow through it.
The reason the voltage at A3 (V
A3
) changes with light is because the phototransistor lets
more current pass when more light shines on it, or less current pass with less light. That
current, which is labeled I in the circuit below, also has to pass through the resistor. When
more current passes through a resistor, the voltage across it will be higher. When less
current passes, the voltage will be lower. Since one end of the resistor is tied to GND = 0 V,
the voltage at the V
A3
end goes up with more current and down with less current.