<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Bennet Gedan &#187; programming</title>
	<atom:link href="http://www.gedan.net/taxonomy/categories/programming/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.gedan.net</link>
	<description>Project Engineer, Web Addict (Frankfurt/Main, Germany)</description>
	<lastBuildDate>Sat, 13 Feb 2010 20:37:20 +0000</lastBuildDate>
	
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Finite State Machine Matrix-Style-C-Implementation (Function Pointers Addon)</title>
		<link>http://www.gedan.net/2009/03/18/finite-state-machine-matrix-style-c-implementation-function-pointers-addon/</link>
		<comments>http://www.gedan.net/2009/03/18/finite-state-machine-matrix-style-c-implementation-function-pointers-addon/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 22:21:00 +0000</pubDate>
		<dc:creator>bgedan</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[developement]]></category>
		<category><![CDATA[state machine]]></category>
		<category><![CDATA[Update]]></category>

		<guid isPermaLink="false">http://www.gedan.net/?p=346</guid>
		<description><![CDATA[This is in an example of an implementation of a finite state automaton with function pointers to functions envoked on each state depending on state-machine inputs. The post follows my recent post regarding a state-event matrix implementation of state-machines.]]></description>
			<content:encoded><![CDATA[<p>I posted my solution for Finite State Machines in C using Matrix. Jean-Marc <em>(<a href="http://www.f1hdi.org">f1hdi.org</a>)</em> <a href="http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/#comment-89">commented to that entry</a>:</p>
<blockquote><p>I would love to have the state event matrix not only returning a ‘next state’ and action to do BUT directly calling ‘actions’ functions. A long time ago , when I was at school, I wrote such ptr function call but can’t reproduce it now.<br />
Basically , in your routine below, I would love to replace the ‘return’ by a call to a function which you would have its pointer in the matrix.<br />
Any idea ?</p></blockquote>
<p>The simple answer to Jean-Marc&#8217;s questions is “Yes” and I&#8217;m really sorry that I hadn&#8217;t got the time to answer sooner. The basic idea of using function pointers is the right choice to find a solution for this task.</p>
<p><span id="more-346"></span></p>
<h3>So what are functions pointers basically?</h3>
<p>First of all a pointer is a data type whose value is &#8220;pointing&#8221; to a specific address in memory. &#8220;Dereferencing&#8221; a pointer returns the value stored at that specific address. Defining a pointer is done with an asterisk before the identifier of the variable. A pointer is assigned via the &#8220;adress of&#8221;-operator &amp; and dereferencing a pointer is done with an asterisk before the identifiers name again.</p>
<pre class="brush: c">
    int *a;
    int b=5;

     a = &amp;b; // a is given the adress of b, a = 5
     b = *a + 10; // b = 15
     &amp;b = a; // b is given the adress of a, b = 5</pre>
<p>Function pointers point to the adress of a c-function. Dereferencing a function pointer means to envoke the apropriate function. The syntax for letting a variable point to a function differs from the above example. Pointing to a function is done via</p>
<pre class="brush: c">void main() {

     void (*fp)();

    fp functionPointer = function_a;

    (*fp)();  //prints "a"

    fp functionPointer = function_b;

    (*fp)();  //prints "b"

}

void function_a(void) {
      fprintf("a \n");
}

void function_b(void) {
     fprintf("b\n");
}</pre>
<h3>What to do with function pointers?</h3>
<p>So these are function pointers, but why do whe need them?</p>
<pre class="brush: c">// from: http://www.newty.de/ftp/intro.html#why

float Plus    (float a, float b) { return a+b; }
float Minus   (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide  (float a, float b) { return a/b; }

// Solution with a switch-statement -  specifies which operation to execute
void Switch(float a, float b, char opCode)
{
   float result;

   // execute operation
   switch(opCode)
   {
      case '+' : result = Plus     (a, b); break;
      case '-' : result = Minus    (a, b); break;
      case '*' : result = Multiply (a, b); break;
      case '/' : result = Divide   (a, b); break;
   }

   cout &lt;&lt; \"Switch: 2+5=\" &lt;&lt; result &lt;&lt; endl;         // display result
}

// Solution with a function pointer
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
   float result = pt2Func(a, b);    // call using function pointer
}

// Execute example code
void Replace_A_Switch()
{
   Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
   Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &amp;Minus);
}</pre>
<h3>Changing the Type Definitions from the Matrix-Style-Implementation</h3>
<p>You should have a look at my <a href="http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/">old post on how to implement a Matrix-Style-Implementation of Finite State Machines in C</a>, to understand how the general mechanisms on this implementation work. I won&#8217;t recapitulate theme here.</p>
<p>First off all, you&#8217;ll have to define the generic typedefs for the state-event matrix as mentioned in the older implementation:</p>
<pre class="brush: c">/*****************************************************************
 * typedefs
 *****************************************************************/

typedef enum {
  STATE1,
  STATE2,
  STATE3
} state;

typedef enum {
  NILEVENT,
  EVENT1,
  EVENT2
} event;</pre>
<p>These are exactly the same data types as the approach without function pointers. We&#8217;ll now define a typedef for a function pointer to an action that shall be released in each state, the action-functions and the generic state-machine function:</p>
<pre class="brush: c">typedef void (*action)();

// General functions
void stateEval(event e);
void exit(int status);
void getIOValues(void);

//Actions
void action1_1(void);
void action1_2(void);
void action1_3(void);
void action2_1(void);
void action2_2(void);
void action2_3(void);
void action3_1(void);
void action3_2(void);
void action3_3(void);</pre>
<p>The action function-pointer and state enumerators are combined in a structure typedef used for the function-pointer based state-event matrix:</p>
<pre class="brush: c">typedef struct {
	state nextState;       // Enumerator for the next state
	action actionToDo;     // function-pointer to the action that shall be released in current state
}  stateElement;               // structure for the elements in the state-event matrix</pre>
<p>And finally the state-event matrix will be build-up:</p>
<pre class="brush: c">stateElement stateMatrix[3][3] = {
   { {STATE1, action1_1}, {STATE2, action1_2}, {STATE3, action1_3} },
   { {STATE2, action2_1}, {STATE2, action2_2}, {STATE3, action2_3} },
   { {STATE3, action3_1}, {STATE3, action3_2}, {STATE3, action3_3} }
};</pre>
<p>And this will be the state-machine invocation with function-pointers involved</p>
<p>All these snippets go into the Header-File.</p>
<pre class="brush: c">#include
#include "main.h"

state  currentState = STATE1;

int main()
{
	//Initializations
	event  eventOccured = NILEVENT;
	action actionToDo   = action1_1;

	while(1) {
		// event input, NIL-event for non-changing input-alphabet of FSM
		// in real implementation this should be triggered by event registers e.g.
		// evaluation of complex binary expressions could be implemented to release the events

                int e = 0;             

               printf("----------------\n");
               printf("Event to occure: ");
               scanf("%u",&amp;e);
               stateEval( (event) e); // typecast to event enumeration type
               printf("-----------------\n");

	};
	return (0);
}

/********************************************************************************
 * stateEval (event)
 * in Dependancy of an triggered event, the action wich is required by this
 * transition will be returned. The proper action is determined by the current state the
 * automat holds. The current state will then be transitioned to the requestet next
 * state
 ********************************************************************************/

void stateEval(event e)
{
	//determine the State-Matrix-Element in dependany of current state and triggered event
        stateElement stateEvaluation = stateMatrix[currentState][e];

	//do the transition to the next state (set requestet next state to current state)...
	currentState = stateEvaluation.nextState;
	//... and fire the proper action
	(*stateEvaluation.actionToDo)();
}

/**********************************************************************
 * action functions
 **********************************************************************/

void action1_1() {
  printf("action1.1 \n");
}

void action1_2() {
  printf("action1.2 \n");
}

void action1_3() {
  printf("action1.3 \n");
}

void action2_1() {
  printf("action2.1 \n");
}

void action2_2() {
  printf("action2.2 \n");
}

void action2_3() {
  printf("action2.3 \n");
}

void action3_1() {
  printf("action3.1 \n");
}

void action3_2() {
  printf("action3.2 \n");
}

void action3_3() {
  printf("action3.3 \n");
}</pre>
<h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>September 8, 2008 -- <a href="http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/" title="Finite State Machine Matrix-Style C Implementation">Finite State Machine Matrix-Style C Implementation</a></li><li>September 8, 2009 -- <a href="http://www.gedan.net/2009/09/08/updated-wordpress-result-new-design-and-layout-loss-of-recordings/" title="Updated Wordpress, Result: New Design and Layout, Loss of Recordings">Updated Wordpress, Result: New Design and Layout, Loss of Recordings</a></li><li>October 25, 2008 -- <a href="http://www.gedan.net/2008/10/25/new-design/" title="New Design">New Design</a></li><li>July 15, 2008 -- <a href="http://www.gedan.net/2008/07/15/hello-world/" title="Hello world!">Hello world!</a></li><li>February 13, 2010 -- <a href="http://www.gedan.net/2010/02/13/back-again/" title="Back again">Back again</a></li><li>May 24, 2009 -- <a href="http://www.gedan.net/2009/05/24/fedora-11-leonidas-how-to-upgrade/" title="Fedora 11 Leonidas, How to Upgrade">Fedora 11 Leonidas, How to Upgrade</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.gedan.net/2009/03/18/finite-state-machine-matrix-style-c-implementation-function-pointers-addon/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Coin Survival Trip (Fuzzified Path Finding Algorithm)</title>
		<link>http://www.gedan.net/2009/01/18/coin-survival-trip/</link>
		<comments>http://www.gedan.net/2009/01/18/coin-survival-trip/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 22:14:20 +0000</pubDate>
		<dc:creator>bgedan</dc:creator>
				<category><![CDATA[curious]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[Babble]]></category>
		<category><![CDATA[coin-survival-trip]]></category>
		<category><![CDATA[curiosity]]></category>
		<category><![CDATA[friends]]></category>
		<category><![CDATA[Hanoi]]></category>
		<category><![CDATA[traveling]]></category>
		<category><![CDATA[vietnam]]></category>

		<guid isPermaLink="false">http://www.gedan.net/?p=336</guid>
		<description><![CDATA[Fuzzified Path finding: The new sciencetific approach in finding the nearest local pub]]></description>
			<content:encoded><![CDATA[<p>A friend of mine is back-packing in vietnam these days, and wrote me an adorable mail about his impressions and experiences. He mentions a method of traveling around, he himself calls &ldquo;Coin-survival-trip&rdquo;. I&#8217;m citing his german annotations (translation follows below):</p>
<blockquote><p>
Wir haben ein wirklich nettes Vietnam-Reisebegleiter-Buch. Allerdings: Was machen Experten, wie wir? Richtig, wir f&uuml;hren in Hanoi den &bdquo;Coin-survival-trip&ldquo; ein. Dies ist mindestens genau so spannend, wie  einfach zu erklären.</p>
<p>Ziel des Spiels ist es, die n&auml;chste zusagende Bierbar zu finden. Mithilfe eines M&uuml;nzwurfes wird an Kreuzungen entschieden, ob nach links oder rechts abgebogen wird. Gibt es die M&ouml;glichkeit weiter geradeaus zu wandern entscheidet das Bequemlichkeit-Zufallsprinzip. Tritt dies in Kraft wird keine M&uuml;nze geworfen, sondern weiter marschiert.
</p></blockquote>
<p>Translation to english:</p>
<blockquote><p>
We&#8217;ve got a lovely vietnam guide book, but what would experts, like us, use instead? Yes, we&#8217;re going to establish the &ldquo;coin-survival-trip&rdquo; in Hanoi. This is certainly as much fun as easy to explain. </p>
<p>Aim of the game is to find the nearest suitable bar. Entering a crossing, a coin toss decides wether you&#8217;ll have to turn left or right. If there&#8217;s the possibility to walk straight ahead, a random accomodativeness-principle is used. If this principle comes into effect, no coin tossing is used.
</p></blockquote>
<p>If you&#8217;re ever on a journey yourself, spread this idea and do a coin-survival-trip; it&#8217;s such a lovely idea, it has to go &#8217;round the world!</p>
<h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>March 18, 2009 -- <a href="http://www.gedan.net/2009/03/18/did-you-know/" title="Did you know&#8230;">Did you know&#8230;</a></li><li>September 7, 2008 -- <a href="http://www.gedan.net/2008/09/07/lan-partys-heute-und-fruher/" title="LAN-Partys heute und früher">LAN-Partys heute und früher</a></li><li>August 1, 2008 -- <a href="http://www.gedan.net/2008/08/01/interesting-statistics-or-why-art-thou-there/" title="Interesting Statistics or Why Art Thou There">Interesting Statistics or Why Art Thou There</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.gedan.net/2009/01/18/coin-survival-trip/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Finite State Machine Matrix-Style C Implementation</title>
		<link>http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/</link>
		<comments>http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/#comments</comments>
		<pubDate>Sun, 07 Sep 2008 22:36:36 +0000</pubDate>
		<dc:creator>bgedan</dc:creator>
				<category><![CDATA[programming]]></category>
		<category><![CDATA[c]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[developement]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[state machine]]></category>

		<guid isPermaLink="false">http://www.gedan.net/?p=46</guid>
		<description><![CDATA[In this article finite state machines are roughly explained and a special implementation approach with an state-event matrix is given.]]></description>
			<content:encoded><![CDATA[<p>There are several implementations of <a href="http://en.wikipedia.org/wiki/Finite_state_machine">finite state machines</a> avaible, the only drawback most of them are suffering is that they are <a href="http://en.wikipedia.org/wiki/Moore_machine">moore machines</a> (under certain circumstances this means a large number of states) and changing the machines behaviour will change the whole code structure (this means low flexibility and the reprogramming may be a huge cause of defects).</p>
<p>I&#8217;d like to present an Implementation of a FSM, i&#8217;ve found during my student research project that is a <a href="http://en.wikipedia.org/wiki/Mealy_machine">mealy machine</a> and does not require a reprogramming of the underlying structure.</p>
<p><span id="more-46"></span></p>
<p>I realized this implementation in an event-driven structure in <a href="http://www.ni.com/labview/">LabVIEW</a> (g) (file a comment if you&#8217;re interested in that implementation). However i recently needed a state machine implementation in C, and tested some implementations and remebered my old implementation of that matrix-style implementation.</p>
<h3>State Transition Table</h3>
<p>The basic idea of this implementation is that every state machine can be directly represented as a <a href="http://en.wikipedia.org/wiki/State_transition_table">state transition table</a>. I&#8217;ll be using a two-dimensional transition table (matrix), depending of current active state and possible events (see <strong>Table 1</strong>).</p>
<div class="centered">
<table border="0">
<caption><strong>Table 1:</strong> State Transition Table</caption>
<thead>
<tr>
<th></th>
<th>Event 1</th>
<th>Event 2</th>
<th>Event 3</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableHdr">State 1</td>
<td>State 2, Action 2</td>
<td>State 3, Action 1</td>
<td>State 1, Action 4</td>
</tr>
<tr>
<td class="tableHdr">State 2</td>
<td>State 1, Action 3</td>
<td>State 2, Action 1</td>
<td>State 2, Action 3</td>
</tr>
<tr>
<td class="tableHdr">State 3</td>
<td>State 3, Action 1</td>
<td>State 1, Action 4</td>
<td>State 2, Action 2</td>
</tr>
</tbody>
</table>
</div>
<p>e.g. the current state would be &#8216;State 2&#8242; and the second event has been triggered, the machine will initiate &#8216;Action 1&#8242; and stay in &#8216;State 2&#8242;.</p>
<p>This compact representation can easily be derived from any state diagramm. Suchlike tabular structures can be transferred into programming languages without difficulty. This is the main benefit of this representation.</p>
<h3>C Code</h3>
<p>States, events and actions are represented by enumerator typedefinitions. All the rest will be build upon them.</p>
<pre class="brush: c">
/*******************************
 * typedefs
 *******************************/

typedef enum {
       STATE_0,
       STATE_1,
       STATE_2
} state;

typedef enum {
      NILACTION,
      ACTION_1,
      ACTION_2,
      ACTION_3,
      ACTION_4
} action;

typedef enum {
      NILEVENT,
      EVENT_1,
      EVENT_2
} event;

typedef struct {
      state nextState;
      action actionToDo;
}  stateElement;</pre>
<p>Based on these type definitions the state transition table can be developed as a 2D-Array of <tt>stateElement</tt> structs.</p>
<pre class="brush: c">
stateElement stateMatrix[3][3] = {
       { {STATE_0,NILACTION}, {STATE_1,ACTION_1}, {STATE_1,ACTION_4} },
       { {STATE_1,NILACTION}, {STATE_2,ACTION_3}, {STATE_2,ACTION_2} },
       { {STATE_2,NILACTION}, {STATE_0,ACTION_2}, {STATE_1,ACTION_3} }
}</pre>
<p>these definitions and constants can be stored in the header file. Getting the machine running is realized via a basic function.</p>
<pre class="brush: c">
/***************************************
 * prototypes
 ***************************************/
action stateEval(event e);</pre>
<p>This function determines what action will be occasioned depending on the triggered event and sets the new state of the machine. The mechanism behind this function is lightweight.</p>
<pre class="brush: c">action stateEval(event e)
{
	//determine the State-Matrix-Element in dependany of current state and triggered event
       stateElement stateEvaluation = stateMatrix[currentState][e];

	//do the transition to the next state (set requestet next state to current state)...
	currentState = stateEvaluation.nextState;
	//... and fire the proper action
	return stateEvaluation.actionToDo;
}</pre>
<p>All that is done is indexing the <tt>stateMatrix</tt>-Array depending on current state (row) and occured event (column). All things additional needed will be a global constant <tt>currentState</tt> to store the machines state. This could be done in the <tt>main()</tt>-loop. Control of the state machine can be achieved via simple mechanism over the <tt>stateEval()</tt>-function.</p>
<pre class="brush: c">        // this single line is the whole FSM-Call, easy as that!
        actionToDo = stateEval(eventOccured);</pre>
<p>This could be put in an event-triggered interrupt-routine, a while-loop, a for-loop over each triggered event, or whatever is reasonable. The <tt>eventOccured</tt> has to be computed by a special algorithm, for example an combination of more or less complex expressions. In the easiest imaginable way this would be an if-structure:</p>
<pre class="brush: c">if ( T &gt; T_MAX ) {
   eventOccured = overTemperatureEvent;
}</pre>
<p>All these little parts combined lead to a quite simple approach for a state machine implementation in programming languages.</p>
<p>The most convincing part is the state transition table, wich is the only thing &#8211;beneath the states und events type definition&#8211; that has to be changed, to change the whole state machine behaviour. It has a direct connection to state machine theory and the common state diagram representation. Thus making this approach tremendously customizable and understandable.</p>
<h3  class="related_post_title">Related Posts</h3><ul class="related_post"><li>March 18, 2009 -- <a href="http://www.gedan.net/2009/03/18/finite-state-machine-matrix-style-c-implementation-function-pointers-addon/" title="Finite State Machine Matrix-Style-C-Implementation (Function Pointers Addon)">Finite State Machine Matrix-Style-C-Implementation (Function Pointers Addon)</a></li><li>September 8, 2009 -- <a href="http://www.gedan.net/2009/09/08/updated-wordpress-result-new-design-and-layout-loss-of-recordings/" title="Updated Wordpress, Result: New Design and Layout, Loss of Recordings">Updated Wordpress, Result: New Design and Layout, Loss of Recordings</a></li><li>May 24, 2009 -- <a href="http://www.gedan.net/2009/05/24/fedora-11-leonidas-how-to-upgrade/" title="Fedora 11 Leonidas, How to Upgrade">Fedora 11 Leonidas, How to Upgrade</a></li><li>October 25, 2008 -- <a href="http://www.gedan.net/2008/10/25/new-design/" title="New Design">New Design</a></li><li>July 15, 2008 -- <a href="http://www.gedan.net/2008/07/15/hello-world/" title="Hello world!">Hello world!</a></li></ul>]]></content:encoded>
			<wfw:commentRss>http://www.gedan.net/2008/09/08/finite-state-machine-matrix-style-c-implementation/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
