Empowering you to understand your world

Sample Code: Build A PWM LED Dimmer For $12 (Using An MSP430)

The following MSP430 code snippet enables you to press a button on your Launchpad to increment the brightness of an external LED lamp by 10% with each press. If you press it when the brightness is at 100%, it will turn the LED lamp off, just like some conventional LED lanterns do.

The button used in this example is connected to pin 1.3 on the Launchpad.

While the MSP430 microcontrollers have much in common, this example was written specifically for and tested on the MSP430G2553.

uS refers to microseconds.

PWM period: The amount of time that the power is ‘on’.

#include <msp430g2553.h>

int main(void) {
WDTCTL = WDTPW + WDTHOLD;

    P1DIR |= BIT2; //Set pin 1.2 to the output direction
    P1REN |= BIT3; //Enable resistor for pin 1.3.
    P1OUT |= BIT3; 
    P1SEL |= BIT2;
    TA0CCR0 = 1000; //The timer counts up to this.
    TA0CCTL1 = OUTMOD_7;
    TA0CCR1 = 0; //The PWM period, which is 0 uS.
    TA0CTL = TASSEL_2 + MC_1;

while(1)
{
    if ((P1IN & BIT3) != BIT3) { //Listen for button presses.
        __delay_cycles(200000);
        TA0CCR1 = TA0CCR1 + 100; //Increment the PWM period
    if (TA0CCR1 > 1000) { TA0CCR1 = 0; }
    }
}
return 0;
}
Leave a Reply
Subscribe to our newsletter
Get notified when new content is published