Creating new IO with global scope

15 Oct 2011

Hi,

I want to be able to have my program create objects at runtime, depending on an input. I've tried the program below, but it doesnt work.

I think it is because the DigitalOut objects only exist inside the code blocks they are created in, but I don't know how to make them global or persistent.

Suggestions?

Thanks in advance.

#include "mbed.h"

DigitalIn button(p20);

int main() {

    if (button) {
        DigitalOut myled(LED1);
    } else {
        DigitalOut myled(LED4);
    }

    while (1) {
        myled = 1;
        wait(0.2);
        myled = 0;
        wait(0.2);
    }
}
15 Oct 2011

#include "mbed.h"

DigitalIn button(p20);
DigitalOut leds[2] = {LED1, LED4};

int main()
{
    int i;
    while (1)
    {
        i = button;
        leds[i] = 1;
        wait(0.2);
        leds[i] = 0;
        wait(0.2);
    }
}
16 Oct 2011

Hi Igor,

Thanks, thats great!

I think the example I gave was too trivial, what I'm really trying to do is :

#include "mbed.h"
#include "MSCFileSystem.h"

DigitalIn button(p20);

int main() {

    if (button) {
        LocalFileSystem fs("fs");
    } else {
        MSCFileSystem fs("fs");
    }

    FILE *fp = fopen("/fs/file.txt","r");

    while (1) {
      // Do somehting with contents of file.
    }
}

In this scenario, I dont think I can have an array, because the the two objects are different types?

Thanks

16 Oct 2011

You can use two distinct pointers in this case.

int main() {
    LocalFileSystem *lfs = NULL;
    MSCFileSystem *mfs = NULL;
    if (button) {
        lfs = new LocalFileSystem("fs");
    } else {
        mfs = new MSCFileSystem("fs");
    }
    // do stuff
    if ( lfs )
        delete lfs;
    if ( mfs )
        delete mfs;
}