Let's Make Robots!

PWM with the MP430G2231

Hey guys!

I was just messing around with PWM on the TI Launchpad and I want to make an LED simply fade in and out.

Now my problem is, that the LED fades in and out once and then it just jumps to full brightness. I don't know why this happens (on the AVRs I solved the problem by not counting down to 0 and everything was alright but that doesn't seem to do the trick for the MSP430)

Here is my code (the bit that fades the LED):

for(i = 1; i < 999; i += 10){ CCR1 = i; _delay_ms(10);}

for(i = 999; i > 0; i -= 10){ CCR1 = h; _delay_ms(10); }

I hope one of you knows where the problem is!


BTW: _delay_ms() is a simple delay function I wrote based on _delay_cycles(1000);

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

The variable i should be a signed int type, not an unsigned int.

The following loop will run forever, because i will never reach 0, or a negative value.

for(i = 999-1; i > 0; i -= 10)

Thanks RobotFreak! Now it works as expected :)

Yeah if you wait about one minute you'll see it fade out again as if its stuck in the second for loop, then it should jump to full brightness again.

I know that there must be while(1) loop in there. Here's my complete code:


#include <msp430g2231.h>

void _delay_ms(volatile unsigned int length){
    volatile unsigned int delay = 0;
    for(delay = 0; delay < length; delay++){

int main(void){
    WDTCTL = WDTPW + WDTHOLD;                 // Stop watchdog timer
    P1DIR |= BIT6;
    P1SEL |= BIT6;
    CCR0 = 1000-1;   
    CCTL1 = OUTMOD_7;
    CCR1 = 0;
    TACTL = TASSEL_2 + MC_1;
    volatile unsigned int i = 0;   
        for(i = 1; i < 999; i += 10){
            CCR1 = i;
        for(i = 999-1; i > 0; i -= 10){
            CCR1 = i;


the while loop looks good, I suggest you try debugging it which is a useful tool as you learn the MCU

for (i = 999-1;i> 0 i-=10)    what's the -1 for ? i don't think thats the problem but hay

for(i = 999; i >=0 ; i-=10)   <<<<<<????

I could have written 998 to^^


while(1) {

// insert your code here


Oh you're right that line is messed up, but this is not the source of the problem I believe. In the program it actually says

for(i = 1; i < 999; i += 10){ CCR1 = i; _delay_ms(10);}

for(i = 999; i > 0; i -= 10){ CCR1 = i; _delay_ms(10);}

I just used the variable h for testing purpose but that didn't work either... 

I still hope somebody knows what the problem is

in the top line ccr1 = i and in the outher it = h  that might be the problem