Kleine Vorlage wie man eine State Machine in C realisieren kann.
Datei bla.c:
[c]
#include „typedef.h“
#include „state_fkt.h“
#include „change_state_fkt.h“
volatile STATES current_state = STATE_1;
volatile STATES next_state = STATE_1;
int main(void)
{
while (1)
{
// If state changed
if (next_state != current_state)
{
char Interrupts = Interrupt_Register;
Interrupt_Register = off; // IRQ off
exit_current_state(current_state); // Clean up old state
enter_next_state(next_state); // Setup new state
current_state = next_state; // Switch to next state
Interrupt_Register = Interrupts; // IRQ old state
}
// Execute state
switch (current_state)
{
case STATE_1:
fkt_state1();
break;
case STATE_2:
fkt_state2();
break;
case STATE_…:
fkt_state…();
break;
default:
break;
}
}
}
[/c]
Datei typedef.h:
[c]
#ifndef typedef_H
#define typedef_H
typedef enum
{
STATE_1,
STATE_2,
STATE_…
} STATES;
#endif
[/c]
Datei state_fkt.h:
[c]
void fkt_state1(void);
void fkt_state2(void);
void fkt_state…(void);
[/c]
Datei state_fkt.c:
[c]
#include „typedef.h“
extern volatile STATES current_state;
extern volatile STATES next_state;
void fkt_state1(void)
{
// Do magic…
next_state = STATE_2;
}
void fkt_state2(void)
{
// Do magic…
next_state = STATE_…;
}
void fkt_state…(void)
{
// Do magic…
next_state = STATE_…;
}
[/c]
Datei change_state_fkt.h:
[c]
void enter_next_state(STATES next_state);
void exit_current_state(STATES current_state);
[/c]
Datei change_state_fkt.c:
[c]
#include „typedef.h“
void enter_next_state(STATES next_state)
{
switch (next_state)
{
case STATE_1:
// Do magic…
break;
case STATE_2:
// Do magic…
break;
case STATE_…:
// Do magic…
break;
default:
break;
}
}
void exit_current_state(STATES current_state)
{
switch (current_state)
{
case STATE_1:
// Do magic…
break;
case STATE_2:
// Do magic…
break;
case STATE_…:
// Do magic…
break;
default:
break;
}
}
[/c]