![]() C C C
|
State MachinesRead - no comments needed I think // from http://c-faq.com/decl/recurfuncp.html // Mod by JDN // Simple efficent way to model state machines in C #include <stdio.h> typedef void *(*pFunc)(); // for typecast for calling function // States -- you need this forward dcl for the compiler and calling // led-off --> led-on ---| // ^-------------------| // all driven from main (or here setup fct) void *led_on(); // as name indicates ... void *led_off(); void *led_on() { printf("on\n"); return (void *)led_off; // next state } void *led_off() { printf("off \n"); return (void *)led_on; // next state } void main() { pFunc statefunc = led_on, oldfunc = led_on; while(1) { oldfunc = statefunc; // if you want to see the previous state - line can be omitted statefunc = (pFunc)(*statefunc)(); // nice thing of design is you can easily track all state changes bq you will pass by here :-) } return ; // should not get here } Arduino Code - Read - no comments needed I think // from http://c-faq.com/decl/recurfuncp.html // Mod by JDN for Arduino // // Simple efficent way to model state machines in C typedef void *(*pFunc)(); // for typecast for calling function // States -- you need this forward dcl for the compiler and calling // led-off --> led-on ---| // ^-------------------| // all driven from main (or here setup fct) void *led_on(); // as name indicates ... void *led_off(); void *led_on() { digitalWrite(13,HIGH); delay(1000); // sleep for a second return (void *)led_off; // next state } void *led_off() { digitalWrite(13,LOW); delay(1000); // sleep for a second return (void *)led_on; // next state } void setup() { pinMode(13,OUTPUT); } pFunc statefunc = led_on, oldfunc = led_on; /* * The idea * Variable named statefunc(aka state) holds address of next function to be called * when you leave a function you simply return reference to enxt function or state to be called * This address is stored in variable statefunc. * The code loops and call again and now we call next state * Instead of having code in loop you could have it every where like * while (1) { * oldfunc = statefunc; // just if you want to see the previous state - debugging !!! * statefunc = (pFunc)(*statefunc)(); * } * */ void loop() { oldfunc = statefunc; // just if you want to see the previous state - debugging !!! statefunc = (pFunc)(*statefunc)(); }
2023-01-16 23:47:08 CET (C) Jens Dalsgaard Nielsen
|