Go back to the examples list

Servo swipe

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 https://libtungsten.io/static/code/examples/servo_swipe/servo.cpp

#include <carbide.h>
#include <Servo.h>
#include <core.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);

    bool up = true;
    int percent = 0;
    while (1) {
        // Set the servo position
        servo.set(percent);

        // Increment or decrement the position according
        // to the current direction
        if (up) {
            percent++;
            if (percent == 100) {
                percent = 100;
                up = false;
            }
        } else {
            percent--;
            if (percent == 0) {
                percent = 0;
                up = true;
            }
        }

        // Wait for 20 ms
        Core::sleep(20);
    }
}

Makefile [download]
wget https://libtungsten.io/static/code/examples/servo_swipe/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