C C C
|
State MachinesRead - no comments needed I think {}{} from http:c-faq.comdeclrecurfuncp.html Mod by JDN 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() {
printf(“on void led_off() {
printf(“off 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 } from http:c-faq.comdeclrecurfuncp.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)(); }
“THE BEER-WARE LICE NSE” (Revision 42):
jensd@jensd.dk wrote this file.
As long as you retain this notice you
can do whatever you want with this stuff on these pages.
If we meet some day, and you think this stuff is worth it,
you can buy me a beer in return :-)
(C) Jens Dalsgaard Nielsen credit for license this goes to phk@FreeBSD.ORG |