Servo example

Here’s the servo example code from yesterday’s lecture:

//
// A short dsPIC30F4011 servo example
// Written by Ted Burke
// Last updated 25-9-2012
//

#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()
{
	TRISD = 0;

	// Configure PWM for free running mode
	//
	//   PWM period = Tcy * prescale * PTPER = 0.33ns * 64 * PTPER
	//   PWM pulse width = (Tcy/2) * prescale * PDCx
	//
	PWMCON1 = 0x00FF;     // Enable all PWM pairs in complementary mode
	PTCONbits.PTCKPS = 3; // prescale=1:64 (0=1:1, 1=1:4, 2=1:16, 3=1:64)
	PTPER = 9375;         // 20ms PWM period (15-bit period value)
	PDC1 = 1406;          // 1.5ms pulse width on PWM channel 1
	PDC2 = 1406;          // 1.5ms pulse width on PWM channel 2
	PDC3 = 1406;          // 1.5ms pulse width on PWM channel 3
	PTMR = 0;             // Clear 15-bit PWM timer counter
	PTCONbits.PTEN = 1;   // Enable PWM time base

	int counter;

	while(1)
	{
		PDC1 = 800;
		__delay32(10000000);
		PDC1 = 1200;
		__delay32(10000000);
		PDC1 = 1600;
		__delay32(10000000);
	}

	return 0;
}

We also looked at a bit-banging example (generating the pulses by setting RD0 high and low with appropriate delays). Here’s the code:

//
// dsPIC30F4011 bit-banging servo example
// Written by Ted Burke
// Last updated 25-9-2012
//

#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()
{
	int counter;

	// Make all port D pins outputs
	TRISD = 0;

	// Alternate between 1ms and 2ms pulses
	while(1)
	{
		// 100 1ms pulses @ 50Hz
		counter = 0;
		while(counter < 100)
		{
			_LATD0 = 1;
			__delay32(1*30000L); // 1ms delay
			_LATD0 = 0;
			__delay32(19*30000L); // 19ms delay

			counter = counter + 1;
		}

		// 100 2ms pulses @ 50Hz
		counter = 0;
		while(counter < 100)
		{
			_LATD0 = 1;
			__delay32(2*30000L); // 2ms delay
			_LATD0 = 0;
			__delay32(18*30000L); // 18ms delay

			counter = counter + 1;
		}
	}

	return 0;
}

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

2 Responses to Servo example

  1. Pingback: Controlling a Servo Motor | fitzgeraldcathal

  2. Pingback: Servo Control | RoboRoBlog

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