1 copyright micron engineering 2007 finite state machines and micro threads massimo manca micron...

Post on 18-Dec-2015

215 Views

Category:

Documents

2 Downloads

Preview:

Click to see full reader

TRANSCRIPT

1Copyright Micron Engineering 2007

Finite State Machines Finite State Machines and Micro Threadsand Micro Threads

Massimo Manca

Micron EngineeringMicron Engineering

2Copyright Micron Engineering 2007

What is this talk What is this talk about?about?

Finite state machines

UML state chart as FSM notation

UML state chart to C code

UML state charts to C code using MicroFSM

3Copyright Micron Engineering 2007

Finite state machinesFinite state machines

A finite state machine (FSM) or finite state automaton is a model of behavior made of a finite number of states, transitions, and actions.

4Copyright Micron Engineering 2007

Finite state machinesFinite state machines

A finite state machine (FSM) or finite state automaton is a model of behavior made of a finite number of states, transitions, and actions.A state stores information about the past...

5Copyright Micron Engineering 2007

Finite state machinesFinite state machines

A finite state machine (FSM) or finite state automaton is a model of behavior made of a finite number of states, transitions, and actions.A state stores information about the past, a transition indicates a state change due to a fulfilled condition...

6Copyright Micron Engineering 2007

Finite state machinesFinite state machines

A finite state machine (FSM) or finite state automaton is a model of behavior made of a finite number of states, transitions, and actions.A state stores information about the past, a transition indicates a state change due to a fulfilled condition and an action is a description of an activity that is to be performed at a given moment.

7Copyright Micron Engineering 2007

Finite state machinesFinite state machinesAction types:

Entry action: performed entering a state

Exit action: performed exiting a state

Input action: performed depending on present state and input conditions

NOTE: Mealy and Moore FSM don't have exit actions.

8Copyright Micron Engineering 2007

FSM representationFSM representationFSM can be represented using a state diagram as above. Besides this, several state transition table types are used. The most common representation is shown below: the combination of current state and condition shows the next state. The complete actions information can be added only using footnotes. An FSM definition including the full actions information is possible using state tables.

9Copyright Micron Engineering 2007

FSM sequence FSM sequence detectorsdetectorsAcceptors and recognizers (sequence detectors)

produce a binary output, saying either yes or no to answer whether the input is accepted by the machine or not. All states of the FSM are said to be either accepting or not accepting. If when all input is processed the current state is an accepting state, the input is accepted; otherwise it is rejected. As a rule the input are symbols (characters); actions are not used.Above FSM recognize the word sos.

10Copyright Micron Engineering 2007

FSM mathematical FSM mathematical modelmodel

An acceptor FSM is a quintuple (Σ,S,s0,,F), where: Σ is the input alphabet (a finite non empty set of symbols). S is a finite non empty set of states. s

0 is an initial state, an element of S. In a non

deterministic finite state machine, s0 is a set of

initial states. is the state transition function: = S S. F is the set of final states a (possibly empty) subset of S.

11Copyright Micron Engineering 2007

FSM transducer FSM transducer modelsmodels

Transducers generate output based on a given input and/or a state using actions. They are used for control applications. Here two types are distinguished also if in practice mixed models are often used. Using exit actions (unknown in Moore and Mealy models) inside FSM's states allows to achieve optimal solutions minimizing the number of the states easy to code as in the Moore model.

Moore machine

The next state of the FSM depends only on the present state, it uses only entry actions. The main advantage of the Moore model is a simplification of the behaviour.

Mealy machine

The next state of the FSM depends on inputs and present state, it uses only input actions. The use of a Mealy FSM leads often to a reduction of the number of states.

12Copyright Micron Engineering 2007

FSM mathematical FSM mathematical modelmodel

A transducer FSM is a sextuple (Σ,Γ,S,s0,δ,ω) where:

Σ is the input alphabet (a finite non empty set of symbols). Γ is the output alphabet (a finite non empty set of symbols). S is a finite non empty set of states. s0 is the initial state, an element of S. In a non

deterministic finite state machine, s0 is a set of initial states. is the state transition function: = S S. ω is the output function.

If the output function is a function of a state and input alphabet S that definition corresponds to the Mealy model. If the output function depends only on a state S that definition corresponds to the Moore model.

13Copyright Micron Engineering 2007

UML State DiagramsUML State DiagramsThe Unified Modeling Language (UML) state diagram is essentially a state diagram with standardized notation that can describe a lot of things, from computer programs to business processes. State charts were developed by David Harel, to add nesting and other features to flat state machines and were later added to UML and standardized. They are an excellent tool for modeling modules (or classes), sub-systems and interfaces that have many distinct states and complex transitions among them. The following is a brief summary of the notation and behavior of state charts. For a full presentation of the UML state chart notation, see the UML 2.0 specification, available at:

www.omg.org/technology/documents/modeling_spec_catalog.htm

14Copyright Micron Engineering 2007

UML state notationUML state notation

Graphically, UML shows states as boxes with rounded corners

15Copyright Micron Engineering 2007

UML transitions UML transitions notationnotation

Graphically, UML shows states as boxes with rounded corners and transitions as arrows lines.

16Copyright Micron Engineering 2007

UML transitions UML transitions notationnotation

Graphically, UML shows states as boxes with rounded corners and transitions as arrows lines. The transitions are labeled with the event that causes the transition.

17Copyright Micron Engineering 2007

UML transitions UML transitions notationnotation

Graphically, UML shows states as boxes with rounded corners and transitions as arrows lines. The transitions are labeled with the event that causes the transition. A condition called guard can be indicated in square brackets...

18Copyright Micron Engineering 2007

UML transitions UML transitions notationnotation

Graphically, UML shows states as boxes with rounded corners and transitions as arrows lines. The transitions are labeled with the event that causes the transition. A condition called guard can be indicated in square brackets followed by the action(s) that will be taken upon transition.

19Copyright Micron Engineering 2007

UML states detailedUML states detailedA state can be divided in 2 areas: the upper for its name

20Copyright Micron Engineering 2007

UML states detailedUML states detailedA state can be divided in 2 areas: the upper for its name and the lower for its actions. Actions are divided in:entry actions:

executed entering the state

21Copyright Micron Engineering 2007

UML states detailedUML states detailedA state can be divided in 2 areas: the upper for its name and the lower for its actions. Actions are divided in:entry actions:

executed entering the state

do actions: executed inside the state

22Copyright Micron Engineering 2007

UML states detailedUML states detailedA state can be divided in 2 areas: the upper for its name and the lower for its actions. Actions are divided in:entry actions:

executed entering the state

do actions: executed inside the state

exit actions: executed leaving the state

23Copyright Micron Engineering 2007

UML states detailedUML states detailedA state can be divided in 2 areas: the upper for its name and the lower for its actions. Actions are divided in:entry actions:

executed entering the state

do actions: executed inside the state

exit actions: executed leaving the state

event actions: executed due to an event (specified inside a transition)

24Copyright Micron Engineering 2007

The UML notation for state carts introduces new symbols: a pseudo state to mark the initial state

UML pseudo statesUML pseudo states

25Copyright Micron Engineering 2007

UML pseudo statesUML pseudo statesThe UML notation for state carts introduces new symbols: a pseudo state to mark the initial state and a pseudo state to mark the final state.

26Copyright Micron Engineering 2007

UML pseudo statesUML pseudo statesThe UML notation for state carts introduces new symbols: a pseudo state to mark the initial state and a pseudo state to mark the final state. Either connects to the states by a transition that may be completed with the notation seen before with event, guard and action fields.

27Copyright Micron Engineering 2007

UML junction pointUML junction pointTo simplify the graphical design of the state charts UML notation introduces junction points and choice points. Junction points are used to merge and split several transition paths in a state chart diagram because they accept several input and output transitions.

28Copyright Micron Engineering 2007

UML junction pointUML junction pointTo simplify the graphical design of the state charts UML notation introduces junction points and choice points. Junction points are used to merge and split several transition paths in a state chart diagram because they accept several input and output transitions. A junction point always is pointed by transitions of opposite directions that if include split or merge variables may depend on disjoint event parameters.

29Copyright Micron Engineering 2007

UML junction pointUML junction point

NOTE: it is not mandatory that a junction point has transitions to provide every possible conditions to change state. In the above example there isn't a transition for 3<a<0. What does it mean? Simply that for 3<a<0 there will be not a transition to LEFT or RIGHT states and IDLE will remain the active state.

30Copyright Micron Engineering 2007

UML choice pointUML choice pointA choice point always has 1 entering transition and 2 or more exiting transitions implementing a dynamic choice based on the event on the entering transition. The guard conditions are evaluated reaching the choice point so transitions outgoing from choice point have to provide guards to cover all possible conditions. Suggestion: always provide an else condition.

31Copyright Micron Engineering 2007

This FSM describes the procedure to start an engine using a minimum notation:

The power of UML notation is due to its flexibility, it may be used at different level of detail depending by user's needs; the user is responsible to balance the diagram detail and the information contained in the diagram itself.

State chart example 1State chart example 1

32Copyright Micron Engineering 2007

State chart example 2State chart example 2This is a more detailed example used to understand the order of the execution for all the actions inside a state chart:

the execution order from left to right is:lamp.on() printf(“exiting ON”) printf(“to OFF”) lamp.off() printf(“exiting OFF”) printf(“needless”)

33Copyright Micron Engineering 2007

State chart symbols 1State chart symbols 1

Reassuming: these are the basic notational elements that can be used to make up a diagram:

Note: use of flow final is deprecated, use final state instead.

34Copyright Micron Engineering 2007

State chart symbols 2State chart symbols 2

The following are the remaining notational elements that can be used to make up a state diagram. Their use is limited to concurrent states and their synchronization.

35Copyright Micron Engineering 2007

UML state charts to C UML state charts to C codecode

There are 2 main well established methods to convert an UML state chart diagram to C:

A nested switch(..) statement with a scalar state variable used as a discriminator in one level of the switch and the event-type in the other.A state table containing an (typically sparse) array

of transition for each state. The table lists event types (triggers) along one dimension and the states along the other.Both methods have pros and cons, aren't well defined and the implementation robustness depends by the programmer skills. I will propose MicroFSM a set of constructs giving a simple method to translate a state chart to an equivalent C code using simple templates.

36Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

I will propose a simple method to realize a state chart using C code and simple templates.

MicroFSM proof of concept

Very portable, only pure ANSI C

Use the C preprocessor

None assembler required

Realized using the switch() statement under the hood

None library required, only a file to include

Short learning curve

Printed templates to manually code a state chart

37Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

In MicroFSM a state chart have to be entirely contained inside a C function... FsmDeclare(LightFsm(char off));

38Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

In MicroFSM a state chart have to be entirely contained inside a C function... FsmDeclare(LightFsm(char off));

that may have any number of parameters of any type... FsmDeclare(EngineFsm(int reset, char *err));

39Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

In MicroFSM a state chart have to be entirely contained inside a C function... FsmDeclare(LightFsm(char off));

that may have any number of parameters of any type... FsmDeclare(EngineFsm(int reset, char *err));

and returns an int representing its running state... int s = EngineFsm(0, strErr);

40Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

In MicroFSM a state chart have to be entirely contained inside a C function... FsmDeclare(LightFsm(char off));

that may have any number of parameters of any type... FsmDeclare(EngineFsm(int reset, char *err));

and returns an int representing its running state... int s = EngineFsm(0, strErr);

MicroFSM running state can be one of these:

ENDED the fsm ended its execution cycle, at next invocation it will restart from its starting stateEXITED the fsm terminated its executions for everWAITING the execution point is inside a state

41Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

FsmDeclare(LightFsm(char off))

{ FSM_STATES ON=FIRST_STATE, OFF // states declared

... }

In MicroFSM a state chart is made of a set of states...

42Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

FsmDeclare(LightFsm(char off))

{ FSM_STATES ON=FIRST_STATE, OFF // states declar.

FSM_BEGIN // fsm entry point

... FSM_END // fsm end }

In MicroFSM a state chart is made of a set of states...the fsm has its entry point and its block of code...

43Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

FsmDeclare(LightFsm(char off))

{ FSM_STATES ON=FIRST_STATE, OFF // states declar.

FSM_BEGIN // fsm entry point

... FSM_STATE(ON) // this is state ON ... FSM_STATE_END // end state ON FSM_STATE(OFF) // this is state OFF ... FSM_STATE_END // end state ON FSM_END // fsm end }

In MicroFSM a state chart is made of a set of states...the fsm has its entry point and its block of code...every state has its block of code...

44Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

FsmDeclare(LightFsm(char off))

{ FSM_STATES ON=FIRST_STATE, OFF // states declar.

FSM_BEGIN // fsm entry point

... FSM_STATE(ON) // this is state ON if(off) FsmNextState(OFF); FSM_STATE_END // end state ON FSM_STATE(OFF) // this is state OFF ... FSM_STATE_END // end state ON FSM_END // fsm end }

In MicroFSM basically a state chart is a set of states...the fsm has its entry point and its block of code...every state has its block of code...transitions are embedded in the source state...

45Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

...

FSM_STATE(ON) // this is state ON if(off) ...

In MicroFSM a transitions consist in a guard condition to test

46Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

...

FSM_STATE(ON) // this is state ON if(off) print(“exiting ON”); ...

In MicroFSM a transitions consist in a guard condition to test followed by an action (a block of code) to do

47Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

...

FSM_STATE(ON) // this is state ON if(off) { print(“exiting ON”); FsmNextState(OFF); } ...

In MicroFSM a transitions consist in a guard condition to test followed by an action (a block of code) to do and the jump to the new state

THIS IS A TRANSITION

48Copyright Micron Engineering 2007

MicroFSM MicroFSM implementationimplementation

// these 2 blocks are equivalent

...

FSM_STATE(ON) FsmChangeState(off, OFF); ... FSM_STATE(ON) if(off); FsmNextState(OFF); ... ...

FSM_STATE(OFF) FsmTransition(off, printf(“needless”), OFF); ...

To manage the transitions there are more constructs, FsmTransition(guard, exec, nextstate) is the more complete but to conditionally change state without execute any action FsmChangeState(guard, nextstate) is the best one.

THESE ARE ALL THE SAME

TRANSITION

COMPLETE TRANSITION

49Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhood

#define FIRST_STATE -127#define FSM_EXITED 0#define FSM_WAITING 1#define FSM_ENDED 2#define FSM_DECLARE(name_args) int name_args#define FSM_STATES static enum eFsmState {#define END_STATES } eStateCnt=FIRST_STATE; char cSuspend=1;#define FSM_BEGIN END_STATES FSM_START #define FSM_STATE(a) case a :#define FSM_STATE_END break;#define FsmChangeState(cond, nextstate) \ if(cond) eStateCnt=nextstate#define FsmNextState(nextstate) eStateCnt=nextstate#define FsmSuccState() eStateCnt=eStateCnt + 1#define FsmPrevState() eStateCnt=eStateCnt - 1

The complete implementation of MicroFsm is contained in about 60 lines of C preprocessor directives based on switch() instruction and local continuations, these are those discussed in the previous pages:

50Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhood

What are the difference between a FSM implemented with normal switch() construct and MicroFSM?

MicroFSM syntax give prominence to states and transitionsMicroFSM details are hidden on the function containing itMicroFsm flexible syntax permits to realize a function

with FSM and mixed normal procedural codeMicroFSM has pre defined constructs able to solve

common situations as suspend and restart its executionMicroFSM has constructs able to handle pseudo statesMicroFSM execution can continue across 2 or more

states until there is something to wait forMicroFSM syntax masks a more efficient C code MicroFSM can be expanded and adapted to a lof of

situations

51Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhood

What are pseudo states in UML?

The UML state chart notation defines pseudo state the initial and last state symbols because they aren't real states but just a graphic sign evidencing 2 states.

What are pseudo states in MicroFSM?

A pseudo state is every state that can be realized with a blocking wait construct without altering the original behaviour.

What is a blocking wait in MicroFSM?

It is a construct that evaluates a guard condition, if true it will continue the execution flow of the FSM code, if false it will exit from the FSM and next time the execution flow of the FSM will start from the blocking wait construct.

52Copyright Micron Engineering 2007

What blocking wait constructs are provided in MicroFSM?They are:

FsmWaitUntil(condition)FsmWaitWhile(condition)FsmDoWaitUntil(exec, condition)FsmDoWaitWhile(exec, condition)FsmSuspend()FsmSuspendUntil(condition)

and how are implemented blocking wait constructs?They are:

based on local continuationsinspired to proto threads created by Adam Dunkelsdone with switch()...case and enum ANSI C

instructions contained on a C function (also the state variable)

MicroFSM under the MicroFSM under the hoodhood

53Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhood

#define FsmWaitUntil(condition)\ do { \ FSM_SET(eStateCnt); \ if(!(condition)) \ return(FSM_WAITING); \ } while(0)

#define FsmSuspend() \ do { \ cSuspend = 0; \ FsmWaitUntil(cSuspend); \ } while(0)

#define FsmSuspendUntil(cond) \ do { \ cSuspend = 0; \ FsmWaitUntil(cSuspend || !(cond)); \ cSuspend = 1; \ } while(0)

This is the implementation of blocking wait constructs implemented in MicroFsm: page 1

54Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhood

#define FsmWaitWhile(condition) \ FsmWaitUntil(!(condition))

#define FsmDoWaitUntil(exec, condition) \ do { \ FSM_SET(eStateCnt); \ exec; \ if(!(condition)) \ return(FSM_WAITING); \ } while(0)

#define FsmDoWaitWhile(exec, condition) \ FsmDoWaitUntil(!(condition))

This is the implementation of blocking wait constructs implemented in MicroFsm: page 2

55Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhoodAll the magic is contained in a single row:

#define FSM_SET(s) s = (int)__LINE__; case __LINE__:

56Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhoodAll the magic is contained in a single row:

#define FSM_SET(s) s = (int)__LINE__; case __LINE__:

this is the implementation of a local continuation; the __LINE__ macro during compilation is replaced with the current line number as an integer constant. This implementation works inside a MicroFSM because __LINE__ constant can't be equal with any state label that are defined inside FSM_STATES.

57Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhoodAll the magic is contained in a single row:

#define FSM_SET(s) s = (int)__LINE__; case __LINE__:

this is the implementation of a local continuation; the __LINE__ macro during compilation is replaced with the current line number as an integer constant. This implementation works inside a MicroFSM because __LINE__ constant can't be equal with any state label that are defined inside FSM_STATES. The following example...

FSM_STATES ON=FIRST_STATE, OFF // states declarationFSM_BEGIN...

after preprocessing will be expanded as:

58Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhoodAll the magic is contained in a single row:

#define FSM_SET(s) s = (int)__LINE__; case __LINE__:

this is the implementation of a local continuation; the __LINE__ macro during compilation is replaced with the current line number as an integer constant. This implementation works inside a MicroFSM because __LINE__ constant can't be equal with any state label that are defined inside FSM_STATES. The following example...

FSM_STATES ON=FIRST_STATE, OFF // states declarationFSM_BEGIN...

after preprocessing will be expanded as:

static enum eFsmState{ ON=-127, OFF }eStateCnt=-127; char cSuspend=1;switch(eStateCnt) { ...

59Copyright Micron Engineering 2007

MicroFSM under the MicroFSM under the hoodhoodSo notations for transitions and blocking wait

constructs can be intermixed; what is the advantage?

Using MicroFSM a lot of states collapses in pseudo states because in FSMs a lot of states require only one transition

Code is more compact

To convert a FSM to C code we can identify the simpler FSM “building blocks” and convert them to C code, then use them as a set of templates.

60Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templatesThis is a sequence:

...

FsmTransition(guard,event(),B);

... // or

if(guard) {

event();

FsmNextState(B);

}

... // or

if(guard) {

event();

FsmSuccState();

}

... // or

FsmWaitUntil(guard);

event();

61Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templatesThis is an iteration: while(g1) {

if(g2) {

e2();

FsmNextState(B); }

e1();

}

... // or

while(g1) {

FsmWaitUntil(!g1 || g2);

FsmTransition(g2,e2(),B);

}

e1();

}B is supposed to be the next state. Pay attention to choose g1 to be sure that the only way to exit from the while loop is when g2 is evaluated true.

62Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

This is a selection: FsmTransition(g1,e1(),B);FsmTransition(g2,e2(),C);... // orFsmWaitUntil(g1 || g2);if(g1) { FsmNextState(B); e1();}else if(g2) { FsmNextState(C); e2();}... // or FsmWaitUntil(g1 || g2);FsmChangeState(g1,B);FsmChangeState(g2,C);...

63Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

This is always a selection:FsmTransition(g1,e1(),B);FsmTransition(g2,e2(),C);... // orFsmWaitUntil(g1 || g2);if(g1) { FsmNextState(B); e1();}else if(g2) { FsmNextState(C); e2();}... // or FsmWaitUntil(g1 || g2);FsmChangeState(g1,B);FsmChangeState(g2,C);...

64Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

Let's try to add a do action:

FSM_STATE(A)

c++;

FsmTransition(guard, \

event, B);

FSM_STATE_END

... // or

FsmDoWaitUntil(c++,guard);

event();

...

if the action is more complex it may be a block of instructions or a function call for example: FsmDoWaitUntil(b=GainGet(), b>10);

65Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

Let's try to add an exit action:

FSM_STATE(A)

...

if(g1 || g2)

ex();

FsmTransition(g1,e1(), B);

FsmTransition(g2,e2(), C);

FSM_STATE_END

... // or

FsmWaitUntil(g1 || g2);

ex();

FsmTransition(g1,e1(), B);

FsmTransition(g2,e2(), C);

...

66Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

Let's try to add an entry action:

FSM_STATE(Aentry)

entry();

FsmSuccState();

FSM_STATE(A)

FsmTransition(g1,e1,B);

FSM_STATE_END

... // or

entry();

FsmWaitUntil(g1);

e1();

...

67Copyright Micron Engineering 2007

MicroFSM examplesMicroFSM examplesOk, it is time to try a complete simple exercise, we can get the lamp state chart and transform to a complete piece of C code:

68Copyright Micron Engineering 2007

1: FsmDeclare(LightFsm(char off, int gpo)) {2: FSM_STATES ONentry=FIRST_STATE,ON,OFFentry,OFF // states decl.3: FSM_BEGIN4: FSM_STATE(ONentry) // this is entry ON5: lamp.on(); // entry action6: FsmSuccState();7: FSM_STATE(ON)8: if(off) { // transition guard test9: printf(“exiting ON”); // exit action10: FsmSuccState(); // change state11: printf(“to OFF”); // transition action12: }13: FSM_STATE_END // end state 14: FSM_STATE(OFFentry)15: lamp.off(); // entry action16: FsmSuccState();17: FSM_STATE(OFF)18: while(off && !gpo) { // stay here conditions19: if(off || gpo) // transitions guards cond.20: printf(“exiting OFF”); // exit action21: if(gpo) FsmExit(); // test final state guard22: else if(off) printf(“needless”); // auto transition..23: } //... guard test24: FSM_STATE_END25: FSM_END26:}

MicroFSM examplesMicroFSM examples

69Copyright Micron Engineering 2007

MicroFSM examplesMicroFSM examplesThe code is compact and shows from the first line that it implements a FSM; its dedicated syntax give prominence to states and transitions making possible associations label-state and function-transition. So I give a complete description of the code and the implementation.FsmDeclare(LightFsm(char off)) is the C function prototype specialized for FSMs, it is important to say that the function may have an arbitrary number of parameters without requiring any change to te macro. So I may write: FSM_DECLARE(ModemFsm(char input))or: FSM_DECLARE(ModemFsm(char input, int timer))

as required from the specific application.

70Copyright Micron Engineering 2007

All states are listed on a specific line:

FSM_STATES ON=FIRST_STATE, OFF

the first state must be initialized with the required label FIRST_STATE and variable declarations must came before this line.

FSM_BEGINIdentifies FSM starting point; no instruction can be interposed between FSM_STATES and FSM_BEGIN, FSM must end with FSM_END.

FSM_STATE(ON)Identifies ON state entry point as reported in the UML state chart.

FsmSuccState()Implements the transition between ON and OFF states.

MicroFSM examplesMicroFSM examples

71Copyright Micron Engineering 2007

This is an alternative solution using pseudo states constructs:

1: FsmDeclare(LightFsm(char off, int gpo)) {2: FSM_STATES ONentry=FIRST_STATE,ON,OFFentry,OFF // states decl.3: FSM_BEGIN4: FSM_STATE(ON) // this is state ON5: lamp.on(); // entry action6: FsmWaitUntil(off); // transition guard test7: printf(“exiting ON”); // exit action8: printf(“to OFF”); // transition action9: // state OFF10: lamp.off(); // entry action11: while(off && !gpo) { // stay here conditions12: FsmWaitUntil(off || gpo); // transitions guards cond.13: printf(“exiting OFF”); // exit action14: if(gpo) // test final state guard15: FsmExit(); 15: else {16: if(off) //... guard test17: printf(“needless”); // auto transition..18: }19: }20: FSM_STATE_END21: FSM_END22:}

MicroFSM examplesMicroFSM examples

72Copyright Micron Engineering 2007

FsmWaitUntil(off) If off is true the execution will continue on the next instruction otherwise it will exit the FSM and next FSM entry point will be the FsmWaitUntil(...) row.

FsmExit() It will exit from the FSM; next state will be FIRST_STATE.

The main difference with the previous version is that the code is shorter and there isn't FSM_STATE_END for state ON so the execution can pass trough from state A to state B without returning to the calling function.

MicroFSM examplesMicroFSM examples

73Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templatesThis is a template useful to convert a state in a pseudo state when possible. At the end there is the complete code of the FSM template.

FSM_STATE(State) .... FSM_STATE_END

Pseudo states have no label. In next row C is a pseudo state:

//T B->C = FsmWaitUntil(n <= 3);// T C->AFsmWaitUntil(k!=0); //C entry point

74Copyright Micron Engineering 2007

MicroFSM templatesMicroFSM templates

FSM_STATES A=FIRST_STATE, B// C is a pseudo-state so doesn't need to be listed.// T A->B = FsmChangeState(IsBitTrue(GUARD), B); ....// T B->A = FsmChangeState(n<3, A);//T B->C = FsmWaitUntil(n > 3);// T C->A FsmWaitUntil(k==0);

75Copyright Micron Engineering 2007

1: #define BYTE_OF(a, b) (a)2: #define BIT_OF(a,b) (1 << (b))3: #define IsBitTrue(a) istrue(BYTE_OF(a), BIT_OF(a))4: static BYTE s_bStatus; 5: #define GUARD s_bStatus, 66:7: FsmDeclare(TemplateFsm(BYTE bbyte, BYTE bbit, int k)) {8: FSM_STATES A=FIRST_STATE,B // states decl.9: FSM_BEGIN10: FSM_STATE(A) // this is entry ON11: FsmChangeState(IsBitTrue(GUARD), B);12: FSM_STATE_END13: FSM_STATE(B)14: FsmWaitWhile(n==3); // transition guard test15: FsmChangeState(n<3,A); // exit action16: // pseudo state C17: FsmWaitUntil(k==0);18: FsmChangeState(1, A);19: FSM_STATE_END // end state 20: FSM_END21: }22:23: void main(void) {24: int n, r;25: for(n=5; n>=-5; n--)26: r = TemplateFsm(GUARD, n);27: }

MicroFSM templatesMicroFSM templates

top related