Here's a state machine for traffic lights. It might give you ideas:
Code:
#include <stdio.h>
#include <unistd.h>
enum State { state_all_stop, state_NS_go, state_NS_stopping, state_WE_go, state_WE_stopping };
enum Light { light_red = 0, light_amber = 1, light_green = 2 };
char *colours[] = {" red ", "amber", "green"};
// Display the traffic lights
void lights(enum Light we, enum Light ns) {
printf("---------------\n");
printf("\n");
printf(" %s \n", colours[ns]);
printf(" |\n");
printf("%s--+--%s\n", colours[we], colours[we]);
printf(" |\n");
printf(" %s \n", colours[ns]);
}
int main(void) {
enum State state = state_all_stop;
while(1) { // Forever
// For each state, decide what to do and
// what the next next state should be
switch(state) {
case state_all_stop:
lights(light_red,light_red);
sleep(3);
state = state_NS_go;
break;
case state_NS_go:
lights(light_green,light_red);
sleep(5);
state = state_NS_stopping;
break;
case state_NS_stopping:
lights(light_amber,light_red);
sleep(2);
state = state_WE_go;
break;
case state_WE_go:
lights(light_red,light_green);
sleep(5);
state = state_WE_stopping;
break;
case state_WE_stopping:
lights(light_red,light_amber);
sleep(2);
state = state_NS_go;
break;
default:
state = state_all_stop;
break;
}
}
return 0;
}