map()
[Math]
double map(double x, double in_min, double in_max, double out_min, double out_max);Description
Maps the value of x from the range of in_min to in_max to the range of out_min to out_max.
Parameters
x: the value to be mapped.
in_min: the minimum value of the input range.
in_max: the maximum value of the input range.
out_min: the minimum value of the output range.
out_max: the maximum value of the output range.
Returns
The mapped value of x.
Example Code
The code reads the value of a potentiometer connected to pin
IN and place the cosine value mapped to the pin
OUT.
void setup() {
pinLabel(0, "IN"); // set the label of pin 0 to "IN"
pinLabel(1, "OUT"); // set the label of pin 1 to "OUT"
pinMode(1, OUTPUT); // set pin 1 as output
pinLabel(2, "VCC"); // set the label of pin 2 to "VCC"
powerPin(2); // set pin 2 as power pin
pinLabel(3, "GND"); // set the label of pin 3 to "GND"
groundPin(3); // set pin 3 as ground pin
}
void loop() {
// read the value of the potentiometer
int val = analogRead(0);
// map the value to the range of 0 to 360
double angle = map(val, 0, 1023, 0, 360);
// calculate the cosine of the angle in radians
double cosVal = cos(angle * PI / 180);
// map the value to the range of 0 to 1023
analogWrite(1, cosVal * 1023);
// delay for 100ms
delay(100);
}
double map(double x, double in_min, double in_max, double out_min, double out_max) {
// maps the value of x from the range of in_min
// to in_max to the range of out_min to out_max
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}