Remember to maintain security and privacy. Do not share sensitive information. Procedimento.com.br may make mistakes. Verify important information. Termo de Responsabilidade
The map()
function in Arduino is a powerful tool that allows you to re-scale a range of numbers into another range. This is particularly useful when dealing with sensor inputs and outputs that need to be adjusted to fit the requirements of your project. The map()
function can be used to convert sensor readings to a different scale, such as converting an analog sensor input to a range suitable for controlling a servo motor. This article will explain the map()
function, its importance, and how to use it effectively in Arduino projects.
Project: In this example project, we will create a simple system to read the input from a potentiometer and use the map()
function to control the position of a servo motor. The objective is to demonstrate how the map()
function can be used to convert the range of the potentiometer (0-1023) to the range of the servo motor (0-180 degrees). This project will help you understand the practical application of the map()
function in real-world scenarios.
Components List:
Examples:
// Include the Servo library to control the servo motor
#include <Servo.h>
// Create a Servo object
Servo myServo;
// Define the pin connected to the potentiometer
const int potPin = A0;
// Variable to store the potentiometer value
int potValue = 0;
// Variable to store the mapped servo position
int servoPos = 0;
void setup() {
// Attach the servo to pin 9
myServo.attach(9);
// Initialize serial communication for debugging
Serial.begin(9600);
}
void loop() {
// Read the value from the potentiometer (0-1023)
potValue = analogRead(potPin);
// Print the potentiometer value to the serial monitor
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
// Map the potentiometer value to a range of 0-180
servoPos = map(potValue, 0, 1023, 0, 180);
// Print the mapped servo position to the serial monitor
Serial.print("Mapped Servo Position: ");
Serial.println(servoPos);
// Set the servo position
myServo.write(servoPos);
// Wait for a short period to allow the servo to move
delay(15);
}
Explanation:
potValue
stores the raw analog input from the potentiometer, and servoPos
stores the mapped value for the servo position.map()
function to convert the potentiometer value (0-1023) to the servo motor range (0-180 degrees).myServo.write()
function.This project demonstrates how the map()
function can be used to scale sensor inputs to a desired range, making it easier to control actuators like servo motors.