Array of DigitalOut Objects

Simple array of DigitalOut objects initialized in the declaration. Primarily for demonstration and for getting accustomed to this compiler and user interface.

#include "mbed.h"

DigitalOut leds[] = {(LED1), (LED2),(LED3)};

int main() {
    int i, previous;
    int numLeds = sizeof(leds)/sizeof(DigitalOut);
    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.2);
        }
    }
}


2 comments

05 Nov 2010

Note that you can use BusOut class to achieve similar functionality. Also, you don't need parentheses around LEDn constants.

05 Nov 2010

Thanks for the tip. I created a version that has both approaches, as a study/learning tool for myself as I find my way around the compiler and the device. Here's the updated version:

 

#include "mbed.h"

DigitalOut leds[] = {LED1, LED2, LED3, LED4};
int numLeds = sizeof(leds)/sizeof(DigitalOut);

BusOut busLeds(LED1, LED2, LED3, LED4);

// prototypes
void chaseDO(void);
void chaseBO(void);

int main() {
    while(1) {
//        chaseDO();  // DigitalOut array version
        chaseBO();  // BusOut version
    }
}

// Use BusOut for the LED chase
void chaseBO(){
    int i;

    for (i = 0; i < numLeds; i++){
        busLeds = 1 << i;
        wait(0.2);
    }
}

// Use DigitalOut for the LED chase
void chaseDO(){

    static int i, previous;

    for (i = 0; i < numLeds; i++){
        if (i == 0) previous = (numLeds - 1);
        else previous = i - 1;
        
        leds[i] = 1;
        leds[previous] = 0;
        wait(0.2);
    }
}

You need to log in to post a comment