Let's say we have a control box with two buttons (button 1 and button 2) and there are three possible operations
1. When the user presses button 1 and then releases it, the text "blue" should be displayed.
2. When user presses button 2, and then releases it, the text "green" should be displayed.
3. When user presses button 1, holds button 1, then presses button 2 then releases button 2, the text "red" should be displayed.
To simulate the two pushbuttons, I have user enter 1 or 0, depending on whether a specific button (button 1 or button 2) is pressed / held or not pressed at all. But it feels clunky doing it that way, so any better ways to simulate the two push buttons so it's more realistic?
My current code is included below (and yes, this is not homework of any sort) Thanks.
Code:#include <stdio.h> #define S0 0 #define WS1 1 #define WS2 2 #define WS3 3 void buttonFSM( int buttonPress[2]); int main() { int buttonArray[2] = {0}; int i; while(1) { for (i = 0; i < 2; i++) { printf("Button %d: ", i+1); scanf("%d", &buttonArray[i]); } if( (buttonArray[0] == -1)) { break; } if( (buttonArray[0] != -1)) { buttonFSM(buttonArray); } else { printf("Program End"); break; } printf("\n"); } printf("\n\n"); return 0; } //******************************* void buttonFSM(int buttonPress[2]) { static char fsm_state = S0; switch(fsm_state) { case(S0): if( (buttonPress[0] == 0 && buttonPress[1] == 0) || (buttonPress[0] == 1 && buttonPress[1] == 1) ) { fsm_state = S0; } else if (buttonPress[0] == 1 && buttonPress[1] == 0) { fsm_state = WS1; } else if (buttonPress[0] == 0 && buttonPress[1] == 1) { fsm_state = WS2; } break; case WS1: if( (buttonPress[0] == 0 && buttonPress[1] == 0) ) { fsm_state = S0; printf("green\n"); } else if (buttonPress[1] == 1 && buttonPress[1] == 1) { fsm_state = WS3; } else { fsm_state = S0; } break; case WS2: if( (buttonPress[0] == 0 && buttonPress[1] == 0) ) { fsm_state = S0; printf("blue\n"); } else { fsm_state = S0; } break; case WS3: if( (buttonPress[0] == 1 && buttonPress[1] == 0) ) { fsm_state = S0; printf("red\n"); } else { fsm_state = S0; } break; default: break; } }