Thursday, August 15, 2013

Controlling servo motor using MSP430 Launchpad 2 ( introduction to timer )

This is the second post about controlling a servo motor with MSP430. In the last post I explained what is PWM and how to use it to control a servo motor.

Now in this post, I'm going to explain how a timer works in MSP430 and how you can use it for generating PWM.

First of all, between all the MCUs that I have worked with, MSP430 has the easiest setting to activate a timer. To generate PWM, the only thing you need to do is set two number for total time and the duty cycle.

 basically the code will be like this:


#include <msp430.h>


/* using Timer A and generate PWM

* code by godman

*/

unsigned int DutyCycle=1650;

void main(void) {

WDTCTL = 0X5A80; // or we can use WDTCTL = WDTPW + WDTHOL


P1DIR = BIT6; //Set P1.6 Output
    
P1SEL = BIT6;   //Set Peripheral Function which is TA1



// set timer value

TACTL = 0x0210; // TA register set, TASSEL_2+ID_0+MC_1+TACLR_0+TAIE_0+TAIFG_0

TACCR0 = 22000; // MCU_FREQ/SERVO_FREQ=1100000/50=22000
TACCTL1 = OUTMOD_6;  // set the timer to generating PWM
TACCR1 = DutyCycle; // set duty cycle of PWM 0=550 180=2750

while(1)
                {

                 DutyCycle = 1250;     // it set the servo to 90 degree ( my servo works between 0 to 180)
                 }

}


 I will add explanation later, sorry for now

don't forget to connect all ground together, if you want to try this code on MSP development board or LunchPad.