Go back to the examples list

Servo basics

This example shows how to initialize and control a servomotor. Wire the servo as detailed below and press the button to alternate between left, center and right position.

  • [-] to GND
  • [+] to a 5V power supply idealy, otherwise Vbat if a battery is plugged in (be careful because large servos may draw a large amount of current - use an external power supply)
  • [S] to PA11

servo.cpp [download]
wget http://libtungsten.io/static/code/examples/servo_basics/servo.cpp

#include <carbide.h>
#include <Servo.h>

// The servo will use the TC0B1 channel and output the signal on PA11
const TC::Channel TC_SERVO = TC::TC0_B1;
const GPIO::Pin PIN_SERVO = {GPIO::Port::A, 11, GPIO::Periph::B};

int main() {
    // Init the board
    Carbide::init(true);

    // Initialize the servo
    Servo servo(TC_SERVO, PIN_SERVO);

    // This line is optional, only call setPWMTimings()
    // if your servo expects non-standard timings
    servo.setPWMTimings(800, 2200);

    while (1) {
        // Set the servo to 0% position, turn the red LED
        // on, and wait for a button input
        servo.set(0);
        Carbide::setLedB(false);
        Carbide::setLedR(true);
        Carbide::waitButtonPressed();

        // Set the servo to 50% position, turn the green LED
        // on, and wait for a button input
        servo.set(50);
        Carbide::setLedR(false);
        Carbide::setLedG(true);
        Carbide::waitButtonPressed();

        // Set the servo to 100% position, turn the blue LED
        // on, and wait for a button input
        servo.set(100);
        Carbide::setLedG(false);
        Carbide::setLedB(true);
        Carbide::waitButtonPressed();
    }
}

Makefile [download]
wget http://libtungsten.io/static/code/examples/servo_basics/Makefile

NAME=servo

BOOTLOADER=true
CARBIDE=true

# Available modules : adc dac eic gloc i2c spi tc trng usart
# Some modules such as gpio and flash are already compiled by default
# and must not be added here.
MODULES=tc

# Available utils modules : RingBuffer Servo
UTILS_MODULES=Servo

# The toolchain's bin/ path, don't forget to customize it
# If this directory is already in your PATH, comment this line.
TOOLCHAIN_PATH=/opt/arm-none-eabi/bin/

# Include the main lib makefile
include libtungsten/Makefile