Blink LED on segger embedded studio

93 Views Asked by At

How can I blink 2 Leds at the same time i.e. one at 500ms and the other at 1sec exact time on nrf52840 using Seger embedded as ide. I tried to delay it using the inbuilt delay function but it just halts the processor and can't find the exact answer. I tried the examples on the Seger embedded but I can't find the solution I am beginner so, don't so I don't have that much idea about it. It would be very helpful mentioned to learn mor stuffs on it. Thank you!

1

There are 1 best solutions below

0
Clifford On

There are many ways you could do that some more sophisticated than others involving hardware timers, interrupts etc.

However in general, with the little information you have provided and in "pseudocode", a simple solution is to use a much shorter delay and count the number of "ticks" and toggle each LED when it is time to do so:

static const uint32_t LED1_PERIOD = 500 ;
static const uint32_t LED2_PERIOD = 1000 ;
bool led1 = false ;
bool led2 = false ;
uint32_t led1_time = 0 ;
uint32_t led2_time = 0 ;


for(uint32_t tick_count = 0; ; tick_count++ )
{
    if( led1_time >= LED1_PERIOD )
    {
        led1 = !led1 ;
        led1_time = 0 ;
    }

    if( led2_time >= LED2_PERIOD )
    {
        led2 = !led2 ;
        led2_time = 0 ;
    }

    output( GPIO_LED1, led1 ) ;  
    output( GPIO_LED2, led2 ) ;

    delay( 1 ) ;
    led1_time++ ;
    led2_time++ ;

}

That is quite generalised. For your very specific requirements you could simplify that:

bool led1 = false ;
bool led2 = false ;

for(unsigned count = 0;; count++)
{
    output( GPIO_LED1, led1 ) ;  
    output( GPIO_LED2, led2 ) ;

    delay( 500 ) ;

    led1 = !led1 ;

    if( (count & 0x01) != 0u )
    {
        led2 = !led2 ;
    }
}

If you want to perform other processing whilst flashing the LED and you are not using an RTOS, then you probably don't want a delay at all. Instead you would simply poll an available clock source:

static const uint32_t LED1_PERIOD = CLOCKS_PER_SEC / 2u;
static const uint32_t LED2_PERIOD = CLOCKS_PER_SEC ;
bool led1 = false ;
bool led2 = false ;
uint32_t led1_time = clock() ;
uint32_t led2_time = led1_time ;


for( ;; )
{
    uint32_t now = clock() ;
    if( now - led1_time >= LED1_PERIOD )
    {
        led1 = !led1 ;
        led1_time += LED1_PERIOD ;
    }

    if( now() - led2_time >= LED2_PERIOD )
    {
        led2 = !led2 ;
        led2_time += LED2_PERIOD ;
    }

    output( GPIO_LED1, led1 ) ;  
    output( GPIO_LED2, led2 ) ;

    // Do other work here...
}