You can also control a servo motor from Arduino in a similar way as CircuitPython with Arduino's Servo library.  There are actually quite a few resources and guides for using Arduino to control servos, so this page will just highlight how to use a servo in Arduino in the same way as with CircuitPython from the previous page.  For more exploration of servos and Arduino be sure to check out the entire Arduino Lesson 14: Servo Motors guide.

First make sure your servo is wired to your board exactly as shown on the hardware page of this guide.  You'll also need the Arduino IDE installed and configured to upload to your board.  Remember Arduino sketches have to be written entirely up front and uploaded to the board--you can't interactively control servos like you can with CircuitPython.

To control the duty cycle of the servo signal with Arduino we'll use the Servo library instead of directly controlling the PWM output signal.  This is necessary because Arduino doesn't support as much control over PWM output as CircuitPython.  In particular you can't easily change the frequency of a PWM output to the 50hz value required by servos.  Luckily you can use a library to do this frequency control and PWM signal generation for you internally.

Upload the following sketch to your board and it will move the servo between its two extreme positions (a 1.0 and 2.0 millisecond pulse length):

#include <Servo.h>

// Create a servo instance.
Servo servo;

void setup() {
  // Attach servo output to pin 5.

void loop() {
  // Move to position 0, or a 1.0 millisecond long pulse:
  // Remember the servo module in Arduino takes in a position in degrees
  // from 0 to 180 instead of a pulse length in milliseconds or other value.
  // Delay for a second.
  // Move to position 180, or a 2.0 millisecond long pulse and pause again.

Notice the servo library controls the servo using a slightly different method of specifying the position in degrees instead of the raw PWM pulse length in milliseconds.  Internally the servo library is just converting that position value to a PWM pulse length like you saw with the CircuitPython page of this guide.  You can specify a position of 0 for one extreme (1.0 millisecond long pulse), 90 for the center or middle position (1.5 millisecond long pulse), and 180 for the opposite extreme (2.0 millisecond long pulse).

That's all there is to controlling a servo with Arduino!

This guide was first published on Jan 15, 2018. It was last updated on Oct 12, 2022.

This page (Arduino) was last updated on Dec 13, 2017.

Text editor powered by tinymce.