Example Code for Arduino-Mega
Last revision 2026/01/16
The article focuses on using Arduino Mega to control motor angles precisely, providing software setup instructions, wiring diagrams, and sample code to achieve efficient servo movement and angle measurement with the Herkulex library.
Software Preparation
- Development tool: Arduino IDE (download link: Arduino IDE)
- Library: Herkulex Arduino library
- Library Manual: Arduino library Manual
Wiring Diagram

Other Preparation Work
- Mega has multiple Hardware Serial ports - no need for Software Serial
- Verify your motor ID (default: 0xfe)
Sample Code
#include <Herkulex.h>
int n=0xfe; //motor ID - verify your ID !!!!
void setup()
{
delay(2000); //a delay to have time for serial monitor opening
Serial.begin(115200); // Open serial communications
Serial.println("Begin");
Herkulex.beginSerial1(115200); //open serial port 1
Herkulex.reboot(n); //reboot first motor
delay(500);
Herkulex.initialize(); //initialize motors
delay(200);
}
void loop(){
Serial.println("Move Angle: -100 degrees");
Herkulex.moveOneAngle(n, -100, 1000, LED_BLUE); //move motor with 300 speed
delay(1200);
Serial.print("Get servo Angle:");
Serial.println(Herkulex.getAngle(n));
Serial.println("Move Angle: 100 degrees");
Herkulex.moveOneAngle(n, 100, 1000, LED_BLUE); //move motor with 300 speed
delay(1200);
Serial.print("Get servo Angle:");
Serial.println(Herkulex.getAngle(n));
}
Was this article helpful?
