1

I'm currently working with the MSP430G2553, which is coded in C.
For some reason I seem to be awful at coding basic For and While loops, and I can't figure out how to make a While loop take longer to complete after every iteration.

Basically, I have an LED blinking at 100ms on startup.

When I hold a button, I want to make the LED blink slower and slower the longer I hold the button.

When I let go, the LED should keep its slowed-down blinking rate.

Then, a second button will reset the LED blink-rate back to 100ms.

Right now, I'm able to slow down the LED blinking when I hold the button, but it does not keep going slower. Honestly, I'm not sure how to go about doing this so I made an account here and posted.

for(;;) //loop forever
{
    if((P1IN & BIT3)==BIT3) //if button is not pressed
    {
        i = 0;
        a = 4000; //At 10000, 4 cycles per second, or 250ms delay. 4000 cycles = 100ms or 10Hz delay.
        P1OUT ^= BIT0 + BIT6; //two LEDs
        while(i < a) //delays LED blinking until while-loop is complete.
        {
            i = i + 1;
        }
    }
    else if((P1IN & BIT3)!=BIT3) //if button is pressed
    {
        i = 0;
        a = 10000;
        P1OUT ^= BIT0 + BIT6;
        while(i < a) //delays LED blinking until while-loop is complete.
        {
            a = a + 2;
            i = i + 1;
        }
    }
}
dvhh
  • 4,724
  • 27
  • 33
Martian
  • 11
  • 1
  • Thanks guys, I understand that the CPU load will be pretty much at 100% capacity due to ugly for-loops, but right now I'm apparently terrible at transferring these for-loops into an interrupt block. Also I've had some trouble even making the MSP430's clock change in value over a length of time. So for now I'm just trying to hash out the logic needed to make this happen before I transfer into proper CPU coding. – Martian Oct 04 '17 at 01:56

1 Answers1

1

You would need to keep a "global" ( outside of the for scope ) delay counter to keep track of the last button press, or the delay

int button1Pressed = 0; // "global" flag
for(;;) 
{
    if((P1IN & BIT3) != BIT3) // if button pressed
    {
        button1Pressed = 1;
    }
    if((P1IN & BIT4) != BIT4) // hypothetical button 2 press
    {
        button1Pressed = 0;
    }
    int delay = 4000;
    if(button1Pressed) 
    {
        delay = 10000;
    }
    while(delay>0) {
        delay = delay - 1;
    }
}
dvhh
  • 4,724
  • 27
  • 33