More LEDs!

Having mastered a single LED, let's progress to multiple LEDs:

// Blink the all platform LEDs in unison.

#include "libplatform/platform.h"

static void
write_all_leds(int state)
{
  int index;

  // Iterate over all platform LEDs.
  for (index = 0; index < PLATFORM_LED_COUNT; ++index)
    platform_write_led(index, state);
}

void
main(void)
{
  // Initialize platform.
  platform_initialize();

  // Blink all LEDs forever.
  for (;;)
    {
      write_all_leds(1);            // All LEDs on
      platform_spin_delay_ms(500);  // Wait
      write_all_leds(0);            // All LEDs off
      platform_spin_delay_ms(500);  // Wait
    }
}

This example is only slightly more complex than before. The function write_all_leds iterates over all LEDs that the platform provides and sets them all to the same state.

The noteworthy item here is that PLATFORM_LED_COUNT is a count of the number of user-controllable LEDs that the target platform offers. There may well be more LEDs on the target board, but they usually indicate healthy power supplies or USB status and so on, and are not programmable.

When you run this, all LEDs on the target board flash in unison.

Note

PLATFORM_LED_COUNT expands to a numeric constant that enables static allocation of arrays, for example:

static float led_duty_cycle[PLATFORM_LED_COUNT];
Independence for LEDs

Rather than blink all LEDs in unison, it's visually appealing to pulse them, in turn, quickly:

// Chase LEDs around the board.

#include "libplatform/platform.h"

int
main(void)
{
  int i;

  // Initialize platform.
  platform_initialize();

  // All LEDs off.
  for (i = 0; i < PLATFORM_LED_COUNT; ++i)
    platform_write_led(i, 0);

  // Pulse all LEDs, one at a time, forever.
  for (;;)
    {
      for (i = 0; i < PLATFORM_LED_COUNT; ++i)
        {
          platform_write_led(i, 1);
          platform_spin_delay_ms(10);
          platform_write_led(i, 0);
          platform_spin_delay_ms(200);
        }
    }

  // If we ever get out of here...
  return 0;
}

There are other things you can do with multiple LEDs, such as a classic KITT or Cylon animation. These things, however, are more impressive when you have dedicated LED hardware to control, rather than a limited number of miniature indicator LEDs on an evaluation board.