23 March 2010

Arduino Key Words(3)

Each KEYWORD is a link to the
Arduino Reference page

map(value,fromLow,toLow,fromHigh,toHigh)

Description:Re-maps a number from one range to another.
That is, a value of fromLow would get mapped to toLow,
a value of fromHigh to toHigh,
values in-between to values in-between, etc.

Does not constrain values to within the range,
because out-of-range values are sometimes
intended and useful.
The constrain() function may be used
either before or after this function,
if limits to the ranges are desired.

Note that the "lower bounds" of either range may be
larger or smaller than the "upper bounds"
so the map() function may be used
to reverse a range of numbers,
for example

y = map(x, 1, 50, 50, 1);

The function also handles negative numbers well,
so that this example

y = map(x, 1, 50, 50, -100);

is also valid and works well.

The map() function uses integer math so will not generate fractions,
when the math might indicate that it should do so.
Fractional remainders are truncated,
and are not rounded or averaged.

Parameters

value: .......the number to map
fromLow: .the lower bound of the value's current range
fromHigh: the upper bound of the value's current range
toLow: ......the lower bound of the value's target range
toHigh: .....the upper bound of the value's target range

Returns:The mapped value.

Example

/* Map an analog value to 8 bits (0 to 255) */
void setup() {}

void loop()
{
int val = analogRead(0);
val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);
}

randomSeed(seed)

Description

randomSeed() initializes the pseudo-random number generator,
causing it to start at an arbitrary point in its random sequence.
This sequence, while very long, and random, is always the same.

If it is important for a sequence of values
generated by random() to differ,
on subsequent executions of a sketch,
use randomSeed() to initialize the random number generator
with a fairly random input,
such as analogRead() on an unconnected pin.

Conversely, it can occasionally be useful to use
pseudo-random sequences that repeat exactly.
This can be accomplished by calling randomSeed()
with a fixed number, before starting the random sequence.

Parameters: long, int - pass a number to generate the seed.

long randNumber;

void setup(){
Serial.begin(9600);
randomSeed(analogRead(0));
}

void loop(){
randNumber = random(300);
Serial.println(randNumber);

delay(50);
}


2 comments:

  1. The ladyada cds Photocell example used the
    map() function to reduce the range of an analog input form (0, 1023) down to (0, 255)

    That's why the ladyada reference is there..

    ReplyDelete