Programming

MSP430F2013 PWM Example

Here’s an example of fading an LED using PWM:

//******************************************************************************
/*
LED Fading Example
Raghavendra Rao
12/08/2012

This example demonstrates LED fading using PWM. P1.2 is the output.
*/ 
//******************************************************************************

#include  <msp430x20x3.h>

int fade = 0;
int fade_inc = 5;
int fade_max = 1000;
int fade_min = 1;

void delay(void) {
  volatile unsigned int i;
  for (i=0; i<1000; i++) { } 
}

void main(void)
{  
  WDTCTL = WDTPW + WDTHOLD;  // Stop WDT

  P1DIR |= BIT2;             // P1.2 to output
  P1SEL |= BIT2;             // P1.2 to TA0.1

  CCR0 = fade_max - 1;       // PWM Period
  CCTL1 = OUTMOD_7 + CCIE;   // CCR1 reset/set + enable interrupt
  CCR1 = fade;               // CCR1 PWM duty cycle
  TACTL = TASSEL_2 + MC_1;   // SMCLK, up mode

  _BIS_SR(LPM0_bits + GIE);   // Enter LPM0 + enable General Interrupt
}

// Timer A1 interrupt service routine
#pragma vector=TIMERA1_VECTOR
__interrupt void Timer_A (void)
{
  fade += fade_inc;
  if ((fade > fade_max) || (fade < fade_min))
    fade_inc = -fade_inc;
  CCR1 = fade;                // CCR1 PWM duty cycle
  delay();
}
Advertisements