Hardware Reference
In-Depth Information
Conveniently, the
map
function can handle this automatically; simply swap
the high and low values so that the low value is
255
and the high value is 0.
The
map()
function creates a linear mapping. For example, if your
fromLow
and
fromHigh
values are
200
and
900
, respectively, and your
toLow
and
toHigh
values
are
255
and
0
, respectively,
550
maps to
127
because
550
is halfway between
200
and
900
and
127
is halfway between
255
and
0
. Importantly, however, the
map()
function does not constrain these values. So, if the photoresistor does
measure a value below
200
, it is mapped to a value above
255
(because you are
inverting the mapping). Obviously, you don't want that because you can't pass
a value greater than
255
to the
analogWrite()
function. You can deal with this
by using the
constrain()
function. The
constrain()
function looks like this:
output = constrain(value, min, max)
If you pass the output from the
map
function into the
constrain
function,
you can set the
min
to
0
and the
max
to
255
, ensuring that any numbers above or
below those values are constrained to either
0
or
255
. Finally, you can then use
those values to command your LED! Now, take a look at what that final sketch
will look like (see Listing 3-3).
Listing 3-3:
Automatic Nightlight Sketch—nightlight.ino
//Automatic Nightlight
const int RLED=9; //Red LED on pin 9 (PWM)
const int LIGHT=0; //Lght Sensor on analog pin 0
const int MIN_LIGHT=200; //Minimum expected light value
const int MAX_LIGHT=900; //Maximum Expected Light value
int val = 0; //variable to hold the analog reading
void setup()
{
pinMode(RLED, OUTPUT); //Set LED pin as output
}
void loop()
{
val = analogRead(LIGHT); //Read the light sensor
val = map(val, MIN_LIGHT, MAX_LIGHT, 255, 0); //Map the light reading
val = constrain(val, 0, 255); //Constrain light value
analogWrite(RLED, val); //Control the LED
}
Search WWH ::
Custom Search