c++for-loopnested-loopslednucleo

How do I use a for loop to flash a single LED on and off? (c++) (Mbed Studio) (Nucleo Board)


I am a complete coding noob but I am trying to get all LED's to flash on and off 5 times while specifically using a for loop (it has to be a for loop). The LED in question is attached to a bus (also has to be the case) with the integer assignment of 76.

EDIT: When I try a simple for loop with a counter of 5 and then turn the LED's on and off in the statement it only does it once. It may be simpler to assign my LED flashes to the count in the for loop if this is possible?

My thinking so far is to either design a for loop to repeat the same number two numbers 5 times (76 and 0) and assign the bus to the count in the statement however I am struggling to get my head around how to do this only 5 times (My mind can only perceive creating a nested loop endlessly repeating) or to somehow nest a for loop with the operation I want on the inner loop counting off of the outer loop.

Can anyone tell me if I'm on the right track and if so how to either run my first idea only 5 times or assign my Bus actions to my outer loop for the second?

Code so far is below but I have only managed to get the LEDs to turn on.

PortOut traffic(PortC, 0b0000000001001100);

// The default flash rate is once per second for all tasks

int main()
{
int i;
int b;
traffic = 0;




    // 1. Flash the ALL the LEDs 5 times using a for loop, when finished the LEDs must be OFF

    for (i = 0; i < 5; i= i + 1)
    {
    (printf("i%d\n", i));

    for (b = i; b < 5;)
    { 
         traffic = 76;
    wait_us(1000000);
    traffic = 0;
    }
    }

Many thanks in advance,

Joe.

Tried nesting a for loop to repeat the same two integers 5 times in order to assign the Bus to the count, Only managed to endlessly repeat for loop.

Tried nesting a for loop to count to 5 on the outer loop and flash LED's on the inner loop, Only managed to switch LED's on once.


Solution

  • Your outer loop is counting the quantity of pulses.

    The contents of the loop determine the frequency that an LED is on or off:

    for (int counter = 0; counter < 5; ++counter)
    {
        // Turn on the LEDs
        traffic = 76;
    
        // Wait while the LEDs are on.
        waitus(1000000);
    
        // Turn OFF the LEDs
        traffic = 0;
    
        // Wait while the LEDs are OFF.
        waitus(1000000);
    } // End of a pulse  
    

    The issue is that you a delay after you turn them on and after the LEDs are turned off. You can adjust the different delay amounts; they don't need to be on and off at the same time. The delays should be able to adjust the brightness also.