Example Code for Arduino-Servo Control

Last revision 2026/01/06

The article 'Example Code for Arduino-Servo Control' guides users through the process of controlling up to 12 servos using an Arduino board and the MegaServo library. It details the necessary hardware and software preparations, including the DFR0136 board, FTDI Basic breakout, and potentiometer. The provided sample code demonstrates how to connect servos and a potentiometer to the Arduino board, read potentiometer values, and map them to servo positions. Users are warned about the voltage requirements to avoid damaging the module. The article emphasizes the use of the MegaServo library for efficient servo management, providing a practical example to facilitate learning and application. Additional resources are available for further exploration of the Arduino library.

Hardware Preparation

  • DFR0136 Board: 1, Purchase Link
  • FTDI Basic breakout (@3.3V): 1
  • Servos: Up to 12
  • Potentiometer: 1

Software Preparation

Other Preparation Work

  • A FTDI Basic breakout is required to upload the program (@3.3V)
  • Warning: The controller is working under 3.3V, please do not program it with a 5V FTDI breakout, it will damage the module permanently.
  • Connect the potentiometer to analog pin 0.

Sample Code

#include <MegaServo.h>
#define NBR_SERVOS 12  // the number of servos, up to 48 for Mega, 12 for other boards
#define FIRST_SERVO_PIN 2

MegaServo Servos[NBR_SERVOS] ; // max servos is 48 for mega, 12 for other boards

int pos = 0;      // variable to store the servo position
int potPin = 0;   // connect a pot to this pin.

void setup()
{
  for( int i =0; i < NBR_SERVOS; i++)
    Servos[i].attach( FIRST_SERVO_PIN +i, 800, 2200);
}
void loop()
{
  pos = analogRead(potPin);   // read a value from 0 to 1023
  for( int i =0; i <NBR_SERVOS; i++)
    Servos[i].write( map(pos, 0,1023,0,180));
  delay(15);
}

Result

It can be used as a standard mini Arduino board and can control up to 12 servos.

Additional Information

For more information, check the Arduino library.

Was this article helpful?

TOP