FSM (Finite State Machine) implementation

Hello,if I wanted to implement following Moore FSM (Finite State Machine)


The control button pressed the first time turns the system on with continuous light
When the button is pressed the second time the light becomes intermittent with period
0.5s
If the button is pressed again the system switches off
For button I want to use an interrupt line InterruptIN.
How Can I implement it by mbed?
Can You help me?Thanks

1 Like

Hello,

this is more clear to me, I think.

#include "mbed.h"

DigitalOut led(LED1);
InterruptIn button(BUTTON1);

volatile bool buttonFlag = false;

void PressHandler(){
    if(!buttonFlag){
        buttonFlag = true;
        button.disable_irq();
    } 
}

void Light_On(){
    led = 1;
}

void Light_Off(){
    led = 0;
}

void Light_blink(){
    led = !led;
}

int main()
{
    printf("Running on Mbed OS %d.%d.%d.\n", MBED_MAJOR_VERSION, MBED_MINOR_VERSION, MBED_PATCH_VERSION);
    button.fall(callback(&PressHandler));
    int mode = 1;

    while (true)
    {
        if(buttonFlag){
            mode++;
            if (mode > 3) mode = 1;

            buttonFlag= false;
            button.enable_irq();
        }
        switch (mode) {
            case 1:{
                printf("Led Off\n");
                Light_Off();
                break;
            }
            case 2:{
                printf("Led Blink\n");
                Light_blink();
                break;
            }
            case 3:{
                printf("LED On\n");
                Light_On();
                break;
            }
        }
        thread_sleep_for(500);
    }
}

BR, Jan