Servo control using the dsPIC Output Compare module

This dsPIC30F4011 example program generates a servo control signal with a 20ms period and a fixed pulse width of approximately 1.5ms. The signal is generated using channel 1 of the dsPIC’s Output Compare module, which appears on pin 23 (same pin as RD0).

In this example, output compare channel 1 is driven by Timer 2, which is the default. Timer 2 is a 16-bit counter, so it can only count up to a maximum value of 65535. Here, Fosc is set to 120Mhz, which gives an instruction cycle Tcy = 33.33ns. The desired period of the waveform is 20ms, which therefore corresponds to 600,000 instruction cycles. The Timer 2 prescaler must therefore be set to 64:1 in order to bring the 20ms period within reach.

//
// This dsPIC30F4011 example program controls a
// servo using the output compare module. It just
// moves the servo to one fixed angle and holds it
// there by outputting a 1.5ms once every 20ms.
//
// Written by Ted Burke - last updated 3-10-2013
//

#include <xc.h>
#include <libpic30.h>

// Configuration settings
_FOSC(CSW_FSCM_OFF & FRC_PLL16); // Fosc=16x7.5MHz, Fcy=30MHz
_FWDT(WDT_OFF);                  // Watchdog timer off
_FBORPOR(MCLR_DIS);              // Disable reset pin

int main()
{
    // Configure RD0 and RD1 as outputs
    TRISD = 0b1111111111111100;

    // Configure Output Compare channel 1 (OC1)
    OC1R = 0;               // pulse start time
    OC1RS = 703;            // pulse stop time (1.5ms)
    OC1CONbits.OCM = 0b101; // continuous pulse mode

    // Configure Timer 2 (default timer for output compare)
    PR2 = 9375;             // Timer 2 period (20ms)
    T2CONbits.TCKPS = 0b10; // Timer 2 prescaler 1:64
    T2CONbits.TON = 1;      // Enable Timer 2

    // Flash an LED on RD1 indefinitely at 1Hz
    while(1)
    {
        _LATD1 = 1;          // LED on
        __delay32(15000000); // 500ms delay
        _LATD1 = 0;          // LED on
        __delay32(15000000); // 500ms delay
    }

    return 0;
}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

1 Response to Servo control using the dsPIC Output Compare module

  1. Pingback: Stepper Motor & Servo Motor – Laurence Keighery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s