Chasing LEDs for newbies

This program will alternate between two, three, or all four of the built-in LEDs. How many is determined by opening a Terminal window in OS X (Windows and Linux not yet tried) and typing: screen /dev/tty.usbmodem*

I'm posting this both because other beginners might enjoy it and because I love watching LEDs flash.

The code is modified from that posted by Jeff Bosch in 2010 and from reading the examples about Serial. I've already received significant help in the Forum, thank you. (Example: close screen and get back to Terminal with a CTRL-A, k, and y.).

I would love to see this program re-written elegantly by a pro.

// r. ralston March 2011
// based on code posted last year by Jeff Bosch and Serial examples
// OS X Terminal:    screen /dev/tty.usbmodem*
// Use Cntrl-A, k, and y to exit back to Terminal
// Type 2, 3, or 4 in Terminal window to set # of LEDs being chased.

#include "mbed.h"

DigitalOut leds[] = {LED1,LED2, LED3, LED4};
Serial pc(USBTX, USBRX);

int main() {
    int i, previous;
    char c;
    int numLeds = 2;
    while (1) {
        for (i=0; i<numLeds; i++) {
            if (i==0) previous = (numLeds - 1);
            else previous = (i-1);
            leds[i] = 1;
            leds[previous] = 0;
            wait(0.15);
        }
        if (pc.readable()) c = pc.getc();
        if (c=='2') numLeds = 2;
        if (c=='3') numLeds = 3;
        if (c=='4') numLeds = 4;
        if ((c=='2') || (c=='3') || (c=='4')) {
            leds[0] = leds[1] = leds[2] = leds[3] = i = 0;
        }
    }
}

Here's a short video of keyboard control in action:


Please log in to post comments.