9 years, 7 months ago.

How to assign PinName to a global event (or any other object) at run time?

I would like to be able to create an event object at run time. The calling code would specify the pin to assign as an argument. Hopefully my intentions are clear in the comments in the code below. I also want to do the same with a DigitalIn (pushbutton) but assume whatever the answer is to the question below would extend to that case also.

#include "mbed.h"
#include "InterruptIn.h"

DigitalOut led_red(LED_RED);
DigitalOut led_blue(LED_BLUE);
//  I don't see how to create the object below
//  without assigning a PinName.
InterruptIn myEvent(SW3);

void trigFall() {
    led_red = 1;    // On switch press, turn off the red
    led_blue = 0;   //   led and turn on blue led for 2 sec.
    wait(2.0);      // Then, return to red flashing led
    led_blue = 1;
}

void setUp(PinName swName, void(*tfRoutine)(void)) {
// I want to be able to assign myEvent pin name = swName
//  I.e., the ideal solution would be this:
    myEvent.PinName = swName;  << but, this is an illegal statement

// Next line works, but object disappears on function exit
    InterruptIn myEvent(swName);
    myEvent.fall(tfRoutine);    // once event object is created, this is okay
}

int main() {
    led_blue = 1;
    setUp(SW2, &trigFall);    
    while (true) {
        led_red = !led_red; // toggle red led
        wait(0.5f);
    }
}

1 Answer

9 years, 7 months ago.

Hi Dave,

Interrupt don't run on main loop which would make static parameters useless. However, there are ways to bypass this.

Just a suggestion, not tested at all, but at least these parts don't return error.

Change your setUp for this:

PinName name[4] = { LED1, LED2, LED3, LED4};//etc
volatile bool received = false;

void setUp(PinName swName, void(*tfRoutine)(void))
{
    received = true;
}

And add this to your main:

        if( received) {
            static InterruptIn myEvent(name[3]);
            received = false;
        }

Good luck!

Maxim