Jump to content
Sign in to follow this  
jamesglanville

Easy/Lazy way to drive servos.

Recommended Posts

I needed a way to drive a servo for a reverse geocaching box I'm building, and I wanted a simple way to do it. I found the timers quite confusing, but systick to be a neat and simple way to hide the more complicated timer code: (I stripped away my other code, but this is tested and works). To control more servos, simply add a second variable, say servomson2, and copy the two lines indicated. The code works because with servos you just send the right length pulse every 20ms or so, so you can just "systick" every 1ms (or less if you need finer control), decrement servotimer, and use that to decide whether to turn the output pin on. Hope this helps someone.

 

#include "inc/hw_ints.h" //Not sure all of these includes are needed.
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/debug.h"
#include "driverlib/fpu.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/timer.h"
#include "driverlib/pin_map.h"
#include "driverlib/systick.h"
#include "driverlib/rom.h"
#include "driverlib/sysctl.h"

#define SERVO	GPIO_PIN_4 //On port F

volatile int servomson = 15; //default pulse width 1.5ms, roughly center usually. make similar variables if you want more servos.
volatile int servotimer  = 200; //sends pulse every 20ms

void ServoDriver()
{
	servotimer--;
	if (servotimer==0){servotimer=200;}

	if (servotimer>servomson){GPIOPinWrite(GPIO_PORTF_BASE,SERVO,0);} //This and the line below can be copied to run multiple servos.
	else {GPIOPinWrite(GPIO_PORTF_BASE,SERVO,0xFF);}
}

int
main(void)
{
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                       SYSCTL_XTAL_16MHZ);

	ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF);

    ROM_GPIOPinTypeGPIOOutput(GPIO_PORTF_BASE, SERVO);

	SysTickPeriodSet(SysCtlClockGet()/10000); //Sets ServoDriver() to run every 0.1ms. Finer control easy, just increase the 10000.
	SysTickIntRegister(&ServoDriver);
	SysTickIntEnable();
	SysTickEnable();
    ROM_IntMasterEnable();

    while(1) //This just wiggles the servo around to show how it works.
    {
    	servomson++;
    	if (servomson==20){servomson=10;}
    	SysCtlDelay(ROM_SysCtlClockGet()/3);
    }

}

 

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Sign in to follow this  

×
×
  • Create New...