Tuesday 16 July 2013

Finite State Machine Implementation in C for Real Time Applications

 
Dear Reader,

  In this post, you can find the Finite state Machine Implementation in C useful for real time applications.

Please refer my earlier blog post "Simple finite state Machine for Beginners" to get basics of FSM.

The current implementation of FSM contains three states as STATE_1, STATE_2 and STATE_3 and three events as EVENT_1, EVENT_2, EVENT_3.

FSM works based on the events which are been triggered during at point of time. 

e.g:
Case 1 : If the FSM is in STATE_1 and FSM receives an EVENT_2 then it shall call the respective action function and change it next state as  STATE_2.

 Case 2: If the FSM is in STATE_2 and FSM receives an EVENT_2 then it remains in the same state as STATE_2.
 
 

 Finite State Machine Implementation In C
 ================================

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

/* This program Implements the Finite state Machine which contains
 * 3 states as STATE_1, STATE_2, STATE_3 and 3 EVENTS
 * EVENT_1, EVENT_2, EVENT_3 as depicted below

 STATES/EVENTS  | EVENT_1 | EVENT_2 | EVENT_3 | EVENT_4  
 ======================================================
 STATE_1        |
 ----------------
 STATE_2        |
 ----------------
 STATE_3        |
 ----------------
*/

/*
 * Declare states
 */
typedef enum states
{
   INVALID_STATE = 0,
   STATE_1,
   STATE_2,
   STATE_3,
   MAX_STATES
}FSMStates;

/*
 * Declare Events
 */
typedef enum events
{
   INVALID_EVENT = 0,
   EVENT_1,
   EVENT_2,
   EVENT_3,
   MAX_EVENTS
}FSMEvents;

/* Call back Function */
typedef void (*FSMActionFunc)(void *data1);


/* =========================
 * Declaration of FSMStruct
 * =========================
 * FSM Struct should contain
 * ACTION function and Next State
 */
typedef struct FSM
{
   /* Action Function */
   FSMActionFunc  actionFunc;
   /* Next State */
   FSMStates      nextState;
}FSMStruct;



/* Declare FSMStruct Variable */
FSMStruct FSMArray[MAX_STATES][MAX_EVENTS];

/* The Handle Functions are declared Here */
unsigned char currentState;

void processFSMEvent(unsigned int event);
void handle_FSM_EVENT_1(void *data1);
void handle_FSM_EVENT_2(void *data1);
void handle_FSM_EVENT_3(void *data1);

void  initialiseFSM(void)
{
   /* Memset to FSMArray to Zero */
   memset(FSMArray, 0x00,  sizeof(FSMStruct));

   /* Intial State */
   currentState = STATE_1;

   /* STATE_1 Intialisation */
   FSMArray[STATE_1][EVENT_1].actionFunc = handle_FSM_EVENT_1;
   FSMArray[STATE_1][EVENT_1].nextState  = STATE_1;

   FSMArray[STATE_1][EVENT_2].actionFunc = handle_FSM_EVENT_2;
   FSMArray[STATE_1][EVENT_2].nextState  = STATE_2;
 
   FSMArray[STATE_1][EVENT_3].actionFunc = handle_FSM_EVENT_3;
   FSMArray[STATE_1][EVENT_3].nextState  = STATE_3;

   /* STATE 2 */
   FSMArray[STATE_2][EVENT_1].actionFunc = handle_FSM_EVENT_1;
   FSMArray[STATE_2][EVENT_1].nextState  = STATE_1;
  
   FSMArray[STATE_2][EVENT_2].actionFunc = handle_FSM_EVENT_2;
   FSMArray[STATE_2][EVENT_2].nextState  = STATE_2;

   FSMArray[STATE_2][EVENT_3].actionFunc = handle_FSM_EVENT_3;
   FSMArray[STATE_2][EVENT_3].nextState  = STATE_3;
  
   /* STATE 3 */
   FSMArray[STATE_3][EVENT_1].actionFunc = handle_FSM_EVENT_1;
   FSMArray[STATE_3][EVENT_1].nextState  = STATE_1;

   FSMArray[STATE_3][EVENT_2].actionFunc = handle_FSM_EVENT_2;
   FSMArray[STATE_3][EVENT_2].nextState  = STATE_2;
  
   FSMArray[STATE_3][EVENT_3].actionFunc = handle_FSM_EVENT_3;
   FSMArray[STATE_3][EVENT_3].nextState  = STATE_3;
}

/*
 * Handle Event-1  Fn
 */
void handle_FSM_EVENT_1(void *data1)
{
   char *buffer = (char *)data1;
   printf("--------------------------------------------------------------\n");
   printf("OUTPUT OF FSM :In function handle_FSM_EVENT_1 : %s\n", buffer);
   printf("--------------------------------------------------------------\n");
}
/*
 * Handle Event-2  Fn
 */
void handle_FSM_EVENT_2(void *data1)
{
   char *buffer = (char *)data1;
   printf("--------------------------------------------------------------\n");
   printf("OUTPUT OF FSM : In function handle_FSM_EVENT_2 : %s\n", buffer);
   printf("--------------------------------------------------------------\n");
}
/*
 * Handle Event-3  Fn
 */
void handle_FSM_EVENT_3(void *data1)
{
   char *buffer = (char *)data1;

   printf("--------------------------------------------------------------\n");
   printf("OUTPUT OF FSM : In function handle_FSM_EVENT_3 : %s\n", buffer);
   printf("--------------------------------------------------------------\n");
}
/*
 * processFSMEvent()
 */
void processFSMEvent(unsigned int event)
{
  char data1[20];

  if ((event > INVALID_EVENT) && (event < MAX_EVENTS)) 
   {
     if(event == EVENT_1)
     {
       strcpy(data1, "EVENT_1 Data\n");
     }
     else if(event == EVENT_2)
     {
       strcpy(data1, "EVENT_2 Data\n");
     }
     else
     {
       strcpy(data1, "EVENT_3 Data\n");
     }
    
     /* Call the Respective Action Function */
     FSMArray[currentState][event].actionFunc(data1);


     /* Set the Current State */
     currentState =  FSMArray[currentState][event].nextState;
   }
  else
   {
      printf(" Event is Invalid \n");
   }
}
/*
 * Main fn
 */
int main()
{
   unsigned int event; char ch;

   /* Initialise FSM */
   initialiseFSM();

  do
   {     
      printf("Enter the Event(1-3) To be Trigger in FSM STATE Machine \n");
      scanf("%d", &event);

      /* Process FSM Events */
      processFSMEvent(event);

      printf("Do You Want To Run STATE MACHINE Further ....\n");
      printf("For exit enter 100-> Other wise to Continue Enter any  Number\n");
      scanf("%d", &ch);

   }while(ch!= 100);
}

















Thursday 11 July 2013

BITMAP Implementation in C

Dear Reader,

    In this post, i would like to bring you about BIT MAP and its implementation in C used for real time applications

What is BIT MAP?
   Bit Maps are also called as " BIT Array".
   Bit array means that store bits.

Why  BIT MAPS are required?
   Using Bit Array, applications achieve bit-level parallelism in hardware to perform operations quickly.

Some more Info..

Each bit array is mapped to some domain, the bit values can be interpreted as

1. Dark/Light  2. Absent/Present   3. Locked/Unlocked    4. Valid/Invalid

In other words, there are only two possible values.
  • 1 bit indicates the value is SET in a number
  • 0 bit indicates the value is UNSET in a number
For Bit Maps 
  •     OR (|)  is used to set the bit (e.g  n |= (1<<x) )
  •     AND (&) is used to clear the bit  (e.g   n &= ~(1<<x))
 How to Implement the Bit Maps?

Step 1:  Create a bit Map Array.
             unsigned char bit_map[2];

Step 2: Calculate the Bit Map array Index and shift index (How many bits needs to shift).
            < If the user gives  bit_position  input starts from 1>
            bit_map_array_index = (bit_position - 1) /8   
            shift_Index = (bit_position - 1)%8

           < If the user gives  bit_position  input starts from 0>
            bit_map_array_index = bit_position /8   
            shift_Index = bit_position %8

Step 3: Set the Bit in the Bit Map using
            bit_map[bit_map_array_index] |= (1<<shift_Index)

Step 4: Clear the Bit in the Bit Map using
            bit_map[bit_map_array_index] &=  ~(1<<shift_Index)

 Please find the below program for Better Understanding of Bit Maps in C.

#include<stdio.h>
#include<stdlib.h>

#define EXIT 100

#define BITMAP_LEN 2
#define BYTE_LEN   8

/* Debug OutPut */
void printTheDebugOutput(unsigned char *bit_array)
{
   int i, j;

   /* Array is 2 bit_array[0] and [1] */
   for (i=0 ; i<BITMAP_LEN; i++)
   {
     /* Bits 0..7 */
     for(j=1; j<=BYTE_LEN; j++)
     {
        if(bit_array[i] & (1 << (j-1)))
        {
           printf("In BIT_MAP[%d] the position of Bit SET : %d\n",
                                   i, j);
        }
     }
   }
}

/*
 *  Main() function
 */
int main()
{

  unsigned int bit_position, setOrUnsetBit, ch;

  unsigned char bit_Map_array_index, shift_index;

  /* Declare Bit Array and intialised to Zero
   * This BIT_MAP is generally assigned to one domain.
   * Here BIT MAP (Array of Bits) are used for Debugging Mechanism
   */
  unsigned char bit_map[BITMAP_LEN] = { 0 };
 
  /* In Bit- Maps , there are two options,
   * either  Set (OR |) or  Unset (AND &) bit.
   */
 do
 {
    /* Here the Max number of bits is 16 ranging from 1..16 */
    printf("Enter the Bit position (bit starts from 1 and Ends at 16) \n");
    scanf("%d", &bit_position); 

    /*
     * Set/Unset the Bit Map indicates which bits you want to enable 
     */
    printf(" Do you want to set/unset the Bit (1 or 0) \n");
    scanf("%d", &setOrUnsetBit);

    /* LOGIC as follows */
    /* Find Out the Index and and as well as Shift Index */

    /* It Give output as 0 or 1 ( for Bit Position 1..16) */
    bit_Map_array_index = (bit_position-1) / 8;

    /* Always give output as 0...7 ( for Bit Position 1..16)*/
    shift_index =  (bit_position-1) % 8;

    printf("The bit_position : %d shift Index : %d\n", bit_position, shift_index);

    /* If set is true */
    if( setOrUnsetBit)
     {        
       /* Set the Bit Array */
       bit_map[bit_Map_array_index] |= 1<<shift_index;
               
     }
    else
     { 
        /* Clear the Bit Array */ 
        bit_map[bit_Map_array_index] &= ~(1<<shift_index);
        
     }
    printf(" The Bit MAP Array : %d\n", bit_map[bit_Map_array_index]);
    printTheDebugOutput(bit_map);
   
    printf(" Do You want to Continue then Enter any Number"
           "and for Exit then enter 100\n");
    scanf("%d", &ch);

  }while(ch != 100);

 return 0;
}



Please refer in the blog for DEBUG LOG IMPLEMENTATION USING BIT MAP.



Friday 5 July 2013

BIT WISE Operators -> C Interview Questions

Hi All,

  In this post, i would like to show frequently asked C-FAQs that are being encountered in interviews.

BIT-WISE Operators C-Faqs:

1. How to set particular bit in a number?
To set any bit in a number, Use (OR ) operator.

Number = Number | (1<<x)
'x' indicates the position of the bit
 

2. How to clear particular bit in a number?
To clear any bit in a number, Use (AND ) and (NEG (~)) operator.

Number = Number & ~(1<<x)
 
3. How to toggle or flip particular bit in a number?
 To toggle any bit in a number, Use (^ ) exclusive OR operator. 


Number = Number ^ (1<<x)

4.How to check particular bit is set or not in a number?
To check any bit in a number, Use (& ) And Operator . 

Number & (1<<x) 
                                                      'x' indicates the position of the bit  

5. How to represent the above in MACRO's for Real time code?

#define SET_BIT(Number, bit_position)    Number |= (1<< bit_position)

#define CLEAR_BIT(Number, bit_position)    Number &= ~(1<< bit_position)

#define TOGGLE_BIT(Number, bit_position)    Number ^= (1<< bit_position) 

#define CHECK_BIT_IS_SET_OR_NOT(Number, bit_position)    Number & (1<< bit_position)

6. How to check the number is Even or Odd?

#include<stdio.h>
int main()
{
  int number;
  printf("Enter the Number \n");
  scanf("%d", &number);

  if(number & 1)
    printf(" It is ODD number \n");
  else
    printf(" It is Even number \n");
}
 

6. How to count number of  1's or bits set in a number ?

#include<stdio.h>
int main()
{
  int n, count=0;
  printf(" Enter the Number :\n");
  scanf(" %d", &n);

  while(n)
  {
    n = n&(n-1);
    count ++;
  }
  printf(" No of Bits set count in the Number is %d\n", count);
  return 0;
}

 

7. How to count number of  0's or bits unset in a number ?
 
#include<stdio.h>
#define CHAR_BYTE 8
int main()
{
  unsigned int num, count =0, index;
  printf(" Enter the Integer \n");
  scanf("%d", &num);

  for(index = 0; index < (CHAR_BYTE * sizeof(int)); index++)
  {
     /* check the Bit is Set to Zero */
     if((num & (1 << index)) == 0)
     {
        count ++;
     }

  }
  printf(" The Number of Zero's present in Integer: %d\n", count);
  return 0;
}

 8. How to find out a number  is power of 2  or not? 

 #include<stdio.h>
int main()
{
  unsigned int n;
  printf("Enter the Number \n");
  scanf("%d", &n);

  if((n != 0) && (n & (n-1)) )
      printf(" It is Not power of 2\n");
  else
      printf(" It is power of 2\n");

 return 0;
}



 9. How to Swap two numbers using Bit Wise Operators?  ( Remember as -> (ab, ba, ab)

#include<stdio.h>
int main()
{
   int a, b;
   printf(" Enter the Value of a and b\n");
   scanf("%d %d", &a, &b);
   a = a ^ b;
   b = b ^ a;
   a = a ^ b;
   


/*
   or 
   a = a + b;
   b = a - b;
   a = a - b;
   */
 

   printf("Value of a : %d and b : %d\n", a, b);  
   return 0;
}

10. How to reverse a string with out using Temporary variable?

#include<stdio.h>
#include<string.h>

#define LEN 100 /* Can be changed */
int main()
{
   char str[LEN];   
   unsigned int end, start=0;

   printf(" Enter the String to be reversed  \n");
   scanf("%s", str);

   /* Find out the string Length */
   end = strlen(str)-1;
   /* Iterate through start less than end */
   while(start < end)  
   {
     str[start]   ^= str[end];
     str[end]     ^= str[start];
     str[start]   ^= str[end];
    
     start++;
     end --;
   }

   printf("The Reverse string is : %s\n", str);
   return 0;
}



10. How to reverse Bits of a Number?

#include<stdio.h>
#define SIZE_OF_CHAR 8
int main()
{

    unsigned int i, num, reverse_num= 0;
    unsigned int NO_OF_BITS;

    printf("Enter the number to be reversed \n");
    scanf("%d", &num);

    NO_OF_BITS = SIZE_OF_CHAR * (sizeof(num));

   for(i=0; i<NO_OF_BITS; i++)
   {
       if(num & (1<<i))          -> This similar Logic is used to count 1's & 0's in a number.
       {
           reverse_num = reverse_num | (1<< ((NO_OF_BITS -1)-i));
       }
   }

   printf(" The reverse Num is %d", reverse_num);

}

Please refer the BITMAP tutorial in the BLOG, It is really useful for real time applications.