mercredi 19 novembre 2014

Arduino 'map' function

One useful function when you want to use an analog sensor Arduino have a ready to use function called 'map'. 

syntax:

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

Parameters

value: a value or an analog pin value read

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


The Arduino’s ADCs can read 1024 levels between 0V and 5V, and so the value returned by the analogRead function is an integer in the range 0 through 1023.

--> analogRead(A0);

you read 5V/1024=0,0049V

1 step = 4.9mV

By example if you want to use a 10k potentiometer to switch on two LED, the first one when the potentiometer reach 2K and the second LED from 2,5K to 10K.
The potentiometer will be connected to an analog pin A0, A1…
The start value of the source range is 0 and the end value of the source range 1023.
For the first range (0-2K) you have 0 to 204.6 (1023/5)
For the second range (2.5k to 10k) you have 255.75 to 1023
For the first range the tension will vary from 0 to 1002.54 mV the second range from 1253.175mV to +/- 5000mV. (1023*4.9mV)
The map value will be define like that:
y = map(x, 0, 1023, 0, 10000);
Now with an ‘IF’ condition you can define the two ranges like that:

int z; //the value returned by analogRead is an integer
z = analogRead (A0); // Read the input
if (0<=z<=204.6){   //condition
switch on the first LED;
}
if (255.75<=z<=1023){
switch on the second LED;
}

It’s an interesting function, with only one analog input you can command many buttons with a different resistors value.

In the example see above the potentiometer ranges varies from 2K and the second LED from 2,5K to 10K, I lost 0.5K between the two ranges because I have to consider the potentiometer tolerance.

Aucun commentaire:

Enregistrer un commentaire