Project 2 - Implement the Code for controlling the retraction and extension of Airplane’s landing gear
#include
// Define the states of the landing gear
typedef enum {
GEAR_RETRACTED,
GEAR_EXTENDED
} GearState;
// Define the events
typedef enum {
SWITCH_EXTENDED,
SWITCH_RETRACTED
} GearEvent;
// Function to extend the landing gear
void extendGear() {
printf("Extending landing gear...\n");
// Add code here to control the extension of the landing gear
printf("Landing gear is now extended.\n");
}
// Function to retract the landing gear
void retractGear() {
printf("Retracting landing gear...\n");
// Add code here to control the retraction of the landing gear
printf("Landing gear is now retracted.\n");
}
// Function to handle the gear events and transition the FSM
void handleEvent(GearState* currentState, GearEvent event) {
switch (*currentState) {
case GEAR_RETRACTED:
if (event == SWITCH_EXTENDED) {
extendGear();
*currentState = GEAR_EXTENDED;
} else {
printf("Invalid event.\n");
}
break;
case GEAR_EXTENDED:
if (event == SWITCH_RETRACTED) {
retractGear();
*currentState = GEAR_RETRACTED;
} else {
printf("Invalid event.\n");
}
break;
default:
printf("Invalid state.\n");
break;
}
}
int main() {
GearState currentState = GEAR_RETRACTED;
GearEvent events[] = {SWITCH_EXTENDED, SWITCH_RETRACTED, SWITCH_RETRACTED, SWITCH_EXTENDED};
int numEvents = sizeof(events) / sizeof(events[0]);
for (int i = 0; i < numEvents; i++) {
handleEvent(¤tState, events[i]);
}
return 0;
}
This C code, we define an enumeration for the GearState to represent the states of the landing gear, and an enumeration for the GearEvent to represent the events triggering state transitions. The extendGear() and retractGear() functions simulate the control actions for extending and retracting the landing gear.
The handleEvent() function takes the current state and an event as arguments. It uses a switch statement to determine the current state and perform the appropriate action based on the event. If the current state is GEAR_RETRACTED, it checks if the event is SWITCH_EXTENDED and calls extendGear() to extend the landing gear. If the current state is GEAR_EXTENDED, it checks if the event is SWITCH_RETRACTED and calls retractGear() to retract the landing gear. Invalid events or states are handled with appropriate error messages.
In the main() function, we define an initial state currentState as GEAR_RETRACTED. We then simulate a sequence of events (events) by calling handleEvent() for each event, passing the current state and event. The current state is updated, and appropriate messages are printed.