Read current state of LED_RED, LED_GREEN and LED_BLUE always returns 0

Hi!
I’m setting the internal LED on a KL25Z board in one function and tries to read the current status in another function. But I only get 0 when I read the LED. So my problem is that I dont ever get the correct status…

What I want is to save the current state (what color the internal LED has) do some flashing, and then restore the previous state.

example:
void flashLedFunc()
{
DigitalOut led1(LED_RED);
DigitalOut led2(LED_GREEN);
DigitalOut led3(LED_BLUE);

// Trying to save current status for the LED

int led1Status = led1.read();
int led2Status = led2.read();
int led3Status = led3.read();

led1 = 1; // turn off red 
led2 = 1; // turn off green
led3 = 1; // turn off blue 

here is a loop flashing some colors

// Trying to restore the color
led1 = led1Status ;
led2 = led2Status ;
led3 = led3Status ;
}

Hello,

I don’t see any reason why it shouldn’t work, but your example is not clear to me.
Currently it seems like you have ledX objects and also ledXStatus variables inside a flashLedFunc(), but with that you are not able to access same objects out of scope of that function.

BR, Jan

That is true. I have another function that sets the led status with “local” instances of the Ledx objects.

I assumed that since the DigitalOut is a “hardware” function that I was able to create new instances of a DigitalOut object assign the same pin and read the status.

So the solution is to declare the LedX objects globally and then use these global instances instead of creating new instances inside the functions?

And the variables?

int led1Status = led1.read();
int led2Status = led2.read();
int led3Status = led3.read();

These also look like local.

Not sure how good practice this is

there is also another solution, when you not want to use object as global, just pass it into…

#include "mbed.h"

void SetFlashState(DigitalOut dio, int value) {
    dio.write(value);
}

int GetFlashState(DigitalOut *dio) {
    return dio->read();
}

int main() {
    printf("Mbed  test\n");
    DigitalOut led(LED1);

    while(true)
    {
        SetFlashState(led, !GetFlashState(&led));
        thread_sleep_for(1000);
    }
}

BR, Jan