Servo control example from today’s class using output compare

//
// dsPIC30F4011 servo control using output compare
// Written by Ted Burke - last updated 8-10-2013
//
// This dsPIC30F4011 example program controls a
// servo using the output compare module.
// It moves the servo forwards and backwards
// through six 30-degree steps, moving once
// every second.
//
// The max and min OC1RS values (OC1RS=260 for
// 0 degrees and OC1RS=1070 for 180 degrees)
// were determined by trial and error once the
// servo was mounted in position.
//

#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 = 0b1100;

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

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

    // Create an array of angle positions to step through
    double angle[] = {0.0, 30.0, 60.0, 90.0, 120.0, 150.0,
                      180.0, 150.0, 120.0, 90.0, 60.0, 30.0};
    int n = 0; // step counter

    // Configure max and min OC1RS values
    int min = 260;  // OC1RS value for 0 degrees
    int max = 1070; // OC1RS value for 180 degrees

    // Now just cycle through the angle positions
    while(1)
    {
        // Step to next n value
        n = n + 1;
        if (n == 11) n = 0;

        // update servo angle
        OC1RS = min + (angle[n]/180.0)*(max-min);

        __delay32(30000000); // 1s delay
    }

    return 0;
}

I compiled the program using Microchip’s XC16 compiler. I use the simple build script shown below. Just save the C code above as “main.c” in its own folder and save the commands below in a file called “build.bat” in the same folder. Then, to build the program in a command window, just move to the same folder and run the command “build.bat”.

xc16-gcc main.c -mcpu=30F4011 -Wl,--script=p30F4011.gld
if errorlevel 0 xc16-bin2hex a.out
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

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