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!

Torrentula

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

Oh you’re right that line is

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

Try:while(1) {// insert your

Try:

while(1) {

// insert your code here

}

I know that there must be

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

<code>

#include <msp430g2231.h>

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

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;   
       
    while(1){
       
        for(i = 1; i < 999; i += 10){
            CCR1 = i;
            _delay_ms(10);
        }
       
        for(i = 999-1; i > 0; i -= 10){
            CCR1 = i;
            _delay_ms(10);
        }
    }
}

</code>

I could have written 998 to^^
I could have written 998 to^^

the while loop looks good, I

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

The variable i should be a

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)

good catch

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.

Thanks RobotFreak! Now it

Thanks RobotFreak! Now it works as expected :slight_smile: