Skip to main content

State Machine in C

 State Machine in C tutorial

State Machine will help to do and complete some task where real-time event changes its state (like complete, pending, initial ).

example take: you have write some sensor information data to NVM when  someone press switch,
but writing in NVM it will take some 10ms time if u press two times in 10ms then NVM write will not complete.
1st NVM write will not complet it will write only second one.
if you use State machan you can over come this problem,

Using State Machine (SM) is widely spread over programming. A state MS is an automated scheduled to execute certain functions in correlation with certain events and external signals.


Design decisions of State Machine:

- Representing events
- representing states
- representing transitions
- Distribution of events by StateMachine

Methods and Models of creating an State Machine:

- Switches nested
- Table of states
- OO State Design Pattern
- mixed approach

Cereintele a State Machine:

- Maintenance simple
- minimal memory usage
- efficiency

representation of a common State Machine:



Switch Method Nested

- The states and events are represented by enumeration - At least two levels of statements switching; one for the sending State, the other selection signal.
- Shares of transition are implemented in the declaration switching selection signal

Pro:

- Simple and widely established
- memory footprint small (a single variable containing state)
Cons:
- A little possibility to reuse code
- Distribution Linear time events and signals


example:

Now let’s add some complexity and say we want the LED to turn on for 2 seconds, then off for 1, again on for 1 second and then off for 3 seconds. We could add more if:s, but let’s use a switch this time (and ignore that this could be implemented in other ways, too):

enum states { 
  LED_ON2S,
  LED_OFF1S,
  LED_ON1S,
  LED_OFF3S};
enum states state = LED_ON2S;
int secs = 0;
while(1) {
  switch(state) {
  case LED_ON2S:
    led_on(); // make sure LED is on
    if(secs >= 1) {
      state = LED_OFF1S; // turn LED off on next round
      secs = 0;
    }
    break;
  case LED_OFF1S:
    led_off(); // make sure LED is off
    state = LED_ON1S; // LED back on on next round
    break;
  case LED_ON1S:
    led_on();
    state = LED_OFF3S;
    secs = 0; // next state will need this again
    break;
  case LED_OFF3S:
    led_off();
    if(secs >= 2) {
      state = LED_ON2S; // restart cycle on next round
      secs = 0;
    }
    break;
  }

  sleep(1); // sleep for a second
  secs++;
}

Comments

Popular posts from this blog

CAN INTERVIEW QUESTIONS

Qualifiers and Modifier in C

RTOS Real time operating system interview questions

CAN INTERVIEW QUESTIONS 2

What is UDS protocol

Memory mapping in c

TOP IOT PLATFORMS