Controlling a servo motor with an Arduino is a commonplace and easy assignment. Below is an example code that makes use of the Arduino Servo library to manipulate a servo motor, observed by an evidence of the code.
Arduino Code
Copy code
#include <Servo.h>
Servo myServo;
const int potPin = A0;
void setup() {
myServo.attach(5);
}
void loop() {
int potValue = analogRead(potPin); // Read the potentiometer value (0-1023)
int angle = map(potValue, 0, 1023, 0, 180); // Map the potentiometer value to the servo angle (0-180 degrees)
myServo.write(angle); // Set the servo to the mapped angle
delay(15); // Wait for the servo to reach the position
}
Explanation of the Code
Include the Servo Library:
#include <Servo.H>
This line includes the Servo library, which contains functions to govern servo cars.
Create a Servo Object:
Servo myServo;
This creates a servo object named myServo with a purpose to be used to control the servo motor.
Define Variables:
int potPin = A0;
int potValue = zero;
int perspective = 0;
potPin is the analog pin wherein the potentiometer is hooked up.
PotValue shops the cost study from the potentiometer.
Attitude shops the angle to which the servo can be set.
Setup Function:
void setup()
myServo.Attach(nine);
Serial.Begin(9600);
myServo.Attach(9); attaches the servo motor to pin nine.
Serial.Begin(9600); initializes serial communication at 9600 baud price for debugging purposes.
Loop Function:
void loop()
potValue = analogRead(potPin);
perspective = map(potValue, 0, 1023, 0, a hundred and eighty);
myServo.Write(angle);
Serial.Print("Potentiometer Value: ");
Serial.Print(potValue);
Serial.Print(" => Servo Angle: ");
Serial.Println(attitude);
put off(15);
potValue = analogRead(potPin);
reads the potentiometer value, which ranges from zero to 1023.
Perspective = map(potValue, zero, 1023, zero, a hundred and eighty); maps the potentiometer cost to a servo attitude among 0 and 180 stages.
MyServo.Write(angle);
sets the servo motor to the calculated angle.
The Serial.Print and Serial.Println functions are used to print the potentiometer price and corresponding servo perspective to the serial monitor for debugging.
Delay(15); adds a short put off to permit the servo to reach the favored position smoothly.
Components Required:
Arduino Board (e.G., Arduino Uno)
Servo Motor
Potentiometer
Breadboard and Jumper Wires
Circuit Diagram:
Connect the center pin of the potentiometer to A0 on the Arduino.
Connect the opposite two pins of the potentiometer to 5V and GND.
Connect the servo motor's manage cord to pin 9.
Connect the servo motor's power wires to 5V and GND.
