In: Computer Science
In C code Consider the finite state machine shown below that controls a two story elevator. The elevator has a toggle button that can be in the UP position or the DOWN position, and an LED light that can be RED or GREEN . When the elevator is on the GROUND floor the light is RED, and when the elevator is on the FIRST floor the light is GREEN.
Assume the existence of function
enum Button getButton();
that returns a value of DOWN or UP, given enumeration
enum Button {DOWN, UP};
Note the function getButton() already exists so you do not need to define this function, you just need to call this function.
First, define two additional enumerations named State and LED to represent the values GROUND and FIRST, and RED and GREEN, respectively.
Second, write an infinite while loop that first sets the value of a variable that represents the color of the led to either RED or GREEN according to which floor the elevator is currently stationed. Then call function getButton() to read the current position of the toggle button and reassign the value of a variable to represent the next desired floor state of the elevator to either GROUND or FIRST. Assign the elevator to initially reside on the GROUND floor, and assume the elevator moves infinitely fast and will move to the desired floor immediately when the floor state variable is reassigned.
Only show the enumerations and while loop code. Do not define any functions or an entire program with a main function.
Enumerations :
enum State {GROUND,FIRST};
enum LED {RED,GREEN};
While-loop code:
//Variable declaration
enum LED light; //variable to store led light as RED = 0 or GREEN = 1
enum STATE floor; //variable to store floor state as GROUND = 0 or FIRST = 1
floor = GROUND; //Since initially the elevator is at ground floor(mentioned in the problem statement)
//LOOP starts
while(1)
{
if(floor) //if floor = 1 i.e floor state is First floor
{
light=GREEN; //since floor state is first floor, Led color is green
}
else //else if floor = 0 i.e floor state is Ground floor
{
light=RED; //since floor state is ground floor, Led color is red
}
enum BUTTON btn = getButton(); //to read the current value of the toggle button
if(btn) //when btn = 1 i.e toggle button is UP
{
floor=FIRST; //floor value is set to FIRST i.e 1
}
else //when btn = 0 i.e toggle button is DOWN
{
floor=GROUND; //floor value is set to ground i.e 0
}
}