Hardware Reference
In-Depth Information
max(sensorData, 64); //Returns 100 (sensorData is larger)
constrain()
constrain() is like combining parts of max() and min() at the same time; it
constrains data values to a set range.
value = constrain(data, min, max)
Imagine a light sensor, reading the ambient light inside your living room,
letting you turn the lights on or off. Values may vary between dark (you can still
vaguely see your way around), and bright (comfortable to see, but not blinding).
For a light sensor that gives values between 0 and 1,023, you could set the con-
strain levels to values between 40 and 127. Values below 40 are considered too
dark to have a reliable reading, and values over 127 are too bright. What if a ray
of sunlight hits the sensor? It would still be bright enough to see comfortably,
but the sensor may return the maximum value: 255. Or what would happen if
somebody covered the light sensor, for example, a cat and their incredible sense
of disturbing scientii c experiments by sleeping on your equipment? With no
light at all, the sensor might return 0, and if you ever divide a value by your
sensor reading, you could cause an error (because computers can't divide by 0).
The following code will make sure you receive the sensor data, but constrained
between values of 40 and 127 if the original sensor data was out of those bounds.
sensorValue = constrain(sensorData, 40, 127);
abs()
abs() returns the absolute value of a number, for example, the non-negative value
of the number, without regard to its sign. The absolute value of 2 and -2 is 2.
value = abs(x);
This function is implemented in such a way that only values should be cal-
culated, not the results from mathematical operations or functions.
abs(i++); // Do not do this, the result might not be what you expected
i++; // First calculate
abs(i); // Then use the result
map()
map() remaps a number in one range set to another. It takes a number, a theo-
retical boundary, and remaps that number as if it were in another boundary.
map(value, fromLow, fromHigh, toLow, toHigh);
 
Search WWH ::




Custom Search