Beagle Board -

Demo: Micro Servo Motor

Output a pulse width modulated signal on a Servo Motor.

The Micro Servo Motor can rotate 180 degrees and is usually used in applications such as robotics, CNC machinery, or automated manufacturing. By using the 'analogWrite' function [analogWrite(pin, value, [freq], [callback]), the BeagleBone will send Pulse Width Modulated Signals to control the Servo Motor. The position of the servo motor is set by the length of a pulse. In the following program, the frequency is set at 60Hz, which means that the servo receives a pulse every 16.66ms. The length of the pulse, or the duty cycle, can be changed from 3% to 14.5% and can be changed to rotate the servo motor.

The example below, when run, will adjust the position of the servo motor between its two extremes repeatitively.

More information regarding PWMs can be found on the Wikipedia pulse-width modulation page.


var b = require('bonescript');
var SERVO = 'P9_14';
var duty_min = 0.03;
var position = 0;
var increment = 0.1;

b.pinMode(SERVO, b.OUTPUT);

function updateDuty() {
    // compute and adjust duty_cycle based on
    // desired position in range 0..1
    var duty_cycle = (position*0.115) + duty_min;
    b.analogWrite(SERVO, duty_cycle, 60, scheduleNextUpdate);
    console.log("Duty Cycle: " + 
        parseFloat(duty_cycle*100).toFixed(1) + " %");   

function scheduleNextUpdate() {
    // adjust position by increment and 
    // reverse if it exceeds range of 0..1
    position = position + increment;
    if(position < 0) {
        position = 0;
        increment = -increment;
    } else if(position > 1) {
        position = 1;
        increment = -increment;
    // call updateDuty after 200ms
    setTimeout(updateDuty, 200);

Build and execute instructions

  • Connect the "GND" pin from the Servo Motor to P9_1 of the board
  • Connect the "V+" pin from the Servo Motor to P9_3 of the board
  • Connect a 1kohm resistor to the "PWM" pin of the Servo Motor and to P9_14 of the board.
  • Click "Run" on the code. The value of 'position' will go between 0 and 1 changing by 'increment' amount with updates every 200ms.

See also


Related functions


Where to buy

See it in action

Last updated by jessica.lynne.callaway on Thu Dec 19 2013 22:09:29 GMT-0000 (UTC).