Example Code for Arduino-Servo Control
Last revision 2026/01/18
This article offers a detailed guide to controlling servo motors with Arduino, showcasing hardware and software setup, a wiring diagram, and sample code for the DFRobot Beetle RP2040. The servo moves between 0° and 180° using the Arduino Servo Library.
Hardware Preparation
- DFRobot Beetle RP2040, 1, Purchase Link
- USB Type-C Cable, 1
- Servo Motor (e.g., SG90), 1
Software Preparation
- Arduino IDE: Download Link
- Raspberry Pi Pico/RP2040 SDK: Installed via Arduino Boards Manager (see Getting Started)
- Arduino Servo Library: Included with Arduino IDE (no additional installation required)
Wiring Diagram

- Servo brown wire or black wire (GND) to GND;
- Servo red wire (VCC) to VCC (Don’t connect to the 3V3 power. The power of the servo is large, so 3.3V may not be able to drive the servo normally, and may even damage the main controller);
- Servo yellow wire (signal) to GP3;
Other Preparation Work
- Open Arduino IDE.
- Select "DFRobot Beetle RP2040" as the development board.
- Connect the Beetle RP2040 to your computer.
- Wire the servo to GP3 (D3) as per the diagram.
Sample Code
Function: make the servo connected to the GP3 port turn from 0° to 180°, and then back to 0° from 180°. Repeat the cycle.
#include <Servo.h>
Servo myservo;
void setup() {
myservo.attach(3); // set the port number connected to the servo as D3
}
void loop() {
int pos;
for (pos = 0; pos <= 180; pos += 1) {
myservo.write(pos);
delay(15);
}
for (pos = 180; pos >= 0; pos -= 1) {
myservo.write(pos);
delay(15);
}
}
Result
The servo slowly turns from 0° to 180°, and then returns to 0° from 180°, repeating the cycle.
Additional Information
- Servos require a PWM signal with a 20ms period (50Hz) and a pulse width between 1ms (0°) and 2ms (180°).
- The Arduino Servo Library handles PWM signal generation automatically.
Was this article helpful?
