Hello guys! Welcome back to my blog. Today we are going to see the Arduino map function. so let’s begin.
What is the map() function in Arduino??
The map function in Arduino is a very important function in the calculation, mapping values, and scaling. The map function is used to scale values from one range to another range, to understand it better we will look at an example. Arduino map reduces to complex calculation in a code
So we have x1=0, x2 = 1023
and y1 = 0, y2 = 180
Slope (m) = (y2-y1) / (x2-x1)
= (180 – 0) / (1023 – 0)
Slope (m) = 180/1023
y – y1 = m (x - x1)
y = (180 / 1023) * x
Where x represents
potentiometer values and y represents angle for servo motor. This equation will
give us scale-up values between the potentiometer and servo motor.
Servo.write(y)
The value that we will get
from y will be passed as a parameter in the servo write function which will drive the motor to the desired position as per the rotation of the potentiometer.
We will use float as a data
type store value as values can be in decimal form also we are using floating
point math.
Now for each such
application where mapping of two numbers is required, finding slopes and
calculation can be more time-consuming also calculation mistakes may be due to
human may. So to eliminate such a long lengthy process we have a map() function
in which we have to pass parameters. The map function takes 5 parameters such as
value to be mapped, from low, from high, to low, to high. our map function also
takes a negative number
int angle = map(y,0,1023,0,180);
servo.Write(angle);
Example of map() function -
Controlling servo motor using Potentiometer using map() function
Code -
Now we used the serial monitor to observe the output. To open up the serial monitor, click on Tools > Serial Monitor or use the shortcut (SHIFT + CONTROL + M). You can see the servo motor rotates with reference to the rotating knob of the potentiometer. here we have displayed various angles according to the rotation of knob of potentiometer”. the rotation of the knob can be in a clockwise or anti-clockwise direction which will drive the servo motor in the same direction.
Today we learn about the map Arduino function, where to use the map() function, how to use the Arduino map function, what the map() function does in Arduino, syntax, and the parameters of the map() function. we have seen an example of the map() function using a servo motor and potentiometer.
"I hope you find this IoT blog very helpful to you. In the upcoming lesson, we will see more about IoT sensors till then bye. See you all in my next blog."