Example: control servo angle with a potentiometer

//
// Example for dsPIC30F4011 - control servo angle with potentiometer
// PWM output is on PWM1H (pin 37)
// Potentiometer input (0-5V) is on AN0 (pin 2)
// written by Ted Burke - last updated 27-10-2015
//

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

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

unsigned int read_analog_channel(int n);

int main(void)
{
    // Configure PWM
    // PWM period = PTPER * prescale * Tcy = 9470 * 64 * 33.33ns = 20ms
    _PMOD1 = 0;   // PWM channel 1 mode: 0 for complementary, 1 for independent
    _PEN1H = 1;   // PWM1H pin enable: 1 to enable, 0 to disable
    _PTCKPS = 3;  // PWM prescaler setting: 0=1:1, 1=1:4, 2=1:16, 3=1:64
    PTPER = 9470; // Set PWM time base period to 20ms (15-bit value)
    _PTEN = 1;    // Enable PWM time base to start generating pulses

    // Configure AN0-AN8 as analog inputs
    ADCON3bits.ADCS = 15;  // Tad = 266ns, conversion time is 12*Tad
    ADCON1bits.ADON = 1;   // Turn ADC ON
    
    // Move through fixed sequence
    int v;
    while(1)
    {
        // v is between 0 and 1023
        v = read_analog_channel(0);
        
        // PWM pulse width is between 1ms (PDC1 = 947) and 2ms (PDC1 = 1894)
        PDC1 = 947 + 947*(v/1023.0);
    }
}

// This function reads a single sample from the specified
// analog input. It should take less than 5us when the
// microcontroller is running at 30 MIPS.
// The dsPIC30F4011 has a 10-bit ADC, so the value
// returned is between 0 and 1023 inclusive.
unsigned int read_analog_channel(int channel)
{
    ADCHS = channel;          // Select the requested channel
    ADCON1bits.SAMP = 1;      // Start sampling
    __delay32(30);            // 1us delay @ 30 MIPS
    ADCON1bits.SAMP = 0;      // Start Converting
    while (!ADCON1bits.DONE); // Should take 12 * Tad = 3.2us
    return ADCBUF0;
}
Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

One Response to Example: control servo angle with a potentiometer

  1. Pingback: Controlling a Servo Motor | fitzgeraldcathal

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