Counter using FSM

main.cpp

Committer:
eencae
Date:
2020-12-10
Revision:
0:8fabd65058e2

File content as of revision 0:8fabd65058e2:

/*

2645_FSM_Counter

Sample code from ELEC2645

Demonstrates how to implement a simple FSM counter

(c) Craig A. Evans, University of Leeds, Dec 2020

*/
#include "mbed.h"
#include "platform/mbed_thread.h"   // for putting the thread to sleep

// create a bus for writing to the output (LEDs) at once
BusOut output(LED4,LED3,LED2,LED1);

// array of states in the FSM, each element is the output of the counter
// set the output in binary to make it easier, 0 is LED on, 1 is LED off
int g_fsm[4] = {0b0001,0b0010,0b0100,0b1000};

int main()
{
    int state = 0;

    while(1) {  // loop forever

        output = g_fsm[state];  // output current state

        // check which state we are in and see which the next state should be
        switch(state) {
            case 0:
                state = 1;
                break;
            case 1:
                state = 2;
                break;
            case 2:
                state = 3;
                break;
            case 3:
                state = 0;
                break;
            default:
                error("Invalid state");
                state = 0; //invalid state - call error routine
                // and jump to starting state i.e. state = 0
                break;
        }

        thread_sleep_for(500);  // 500 ms delay
    }
}