Example Code for Arduino-Servo Control with Analog Feedback
Last revision 2026/01/16
The article details the process of controlling a servo motor using Arduino with analog feedback for precise angle positioning. It includes hardware and software setup, a wiring diagram, calibration instructions, and sample code for implementing the feedback control, ensuring accurate and reliable servo operation.
Hardware Preparation
- DFRduino UNO R3 (or similar) x 1
- SER0044 DSS-M15S 270° Metal Servo
- M-M/F-M/F-F Jumper wires
Software Preparation
- Arduino IDE, Click to Download Arduino IDE from Arduino®
Wiring Diagram

Other Preparation Work
Before Usage
There will be some error between each servos. If you want to use the servos with scenes that require precise control, you can calibrate them separately. A quick three-point calibration method is provided here:
- 1. Drive the servo to 90 degrees (1500us), record the actual angle as reference angle A, and record the corresponding feedback analog value a;
- 2. Drive the servo to 0 degrees (500us), record the actual angle as reference angle B, and record the corresponding feedback analog value B:
- 3. Drive the servo to 270 degrees (2500c), record the actual angle as reference angle C, and record the corresponding feedback analog value C
The following formula gives the relationship between Analog value & Angle:
- Actual angle = m * Analog value n
- m=[(A-B)/(a-b) (C-A)/(c-a)]/2
- n=[(Ab-Ba)/(b-a) (Bc-Cb)/(c-b)]/2
If you doesn't need such accurate value, you can use m=0.47;n=-33.4 directly.
Sample Code
#include <Servo.h>
Servo myservo; // create servo object to control a servo
void setup() {
myservo.attach(9); // attaches the servo on pin 9 to the servo object
}
void loop() {
int pos = 0; // variable to store the servo position
uint16_t val;
double dat;
for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
val = analogRead(A0); //Connect Analog pin to A0
dat = (double)val * 0.47 - 33.4;
Serial.print("Position:"); //Display the position on Serial monitor
Serial.print(dat);
Serial.println("Degree"); // waits 15ms for the servo to reach the position
}
for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
myservo.write(pos); // tell servo to go to position in variable 'pos'
delay(15);
val = analogRead(A0); //Connect Analog pin to A0
dat = (double)val * 0.47 - 33.4;
Serial.print("Position:"); //Display the position on Serial monitor
Serial.print(dat);
Serial.println("Degree"); // waits 15ms for the servo to reach the position
}
}
Result
Arduino will drive the servo with D9 pin, and receive the Analog feedback from A0 port.
Was this article helpful?
