Egyszerű állapotgép demonstráció
/*
*
* Egyszerű állapotgép demonstráció
*
* lukacs@jozsef.eu
*/
/* ---------------------------------------------------- */
#include <stdio.h>
#include <unistd.h>
/* ---------------------------------------------------- */
/* ---------------------------------------------------- */
typedef void (*function_pointer)(void *);
typedef struct {
function_pointer ptr;
unsigned char ft;
} SM;
#define SM_STATE(name) void name(SM *_sm_)
#define SM_INIT(sm, name) { sm.ptr = (function_pointer)name; sm.ft = 1; }
#define SM_EXEC(sm) { function_pointer temp = sm.ptr; sm.ptr(&sm); sm.ft = (temp != sm.ptr); }
#define SM_NEXT_STATE(name) _sm_->ptr = (function_pointer)name
#define SM_FIRST ( _sm_->ft )
#define SM_COMPARE(sm, name) ( sm.ptr == (function_pointer)name )
/* ---------------------------------------------------- */
/* ---------------------------------------------------- */
void piros_lampa(int i) {
printf("Piros lámpa:\t%d\n", i);
}
void sarga_lampa(int i) {
printf("Sárga lámpa:\t%d\n", i);
}
void zold_lampa(int i) {
printf("Zöld lámpa:\t%d\n", i);
}
/* ---------------------------------------------------- */
SM sm_lampa;
SM_STATE(L_PIROS);
SM_STATE(L_PIROS_SARGA);
SM_STATE(L_ZOLD);
SM_STATE(L_SARGA);
SM_STATE(L_PIROS) {
static n;
if(SM_FIRST) {
piros_lampa(1);
sarga_lampa(0);
zold_lampa(0);
printf("--\n");
n = 0;
}
n++;
if(5 < n) {
SM_NEXT_STATE(L_PIROS_SARGA);
}
}
SM_STATE(L_PIROS_SARGA) {
static n;
if(SM_FIRST) {
piros_lampa(1);
sarga_lampa(1);
zold_lampa(0);
printf("--\n");
n = 0;
}
n++;
if(2 < n) {
SM_NEXT_STATE(L_ZOLD);
}
}
SM_STATE(L_ZOLD) {
static n;
if(SM_FIRST) {
piros_lampa(0);
sarga_lampa(0);
zold_lampa(1);
printf("--\n");
n = 0;
}
n++;
if(5 < n) {
SM_NEXT_STATE(L_SARGA);
}
}
SM_STATE(L_SARGA) {
static n;
if(SM_FIRST) {
piros_lampa(0);
sarga_lampa(1);
zold_lampa(0);
printf("--\n");
n = 0;
}
n++;
if(1 < n) {
SM_NEXT_STATE(L_PIROS);
}
}
/* ---------------------------------------------------- */
void lin_setup() {
SM_INIT(sm_lampa, L_PIROS);
}
void lin_loop() {
SM_EXEC(sm_lampa);
usleep(300000);
}
/* ---------------------------------------------------- */
void main() {
lin_setup();
while(1) {
lin_loop();
}
}
/* ---------------------------------------------------- */