Create an Arduino program that uses enum to create 6 states and does the followi
ID: 3599834 • Letter: C
Question
Create an Arduino program that uses enum to create 6 states and does the following in the states respectively:
• State 1 – “Running Forward”. Starts a DC motor moving forward (this action should not stop until another State stops it). Trigger State 2.
• State 2 – “Wait for Sensor”. Waiting for either your IR or Ultrasonic sensor to register an object within 10 centimeters. When sensor detects object Trigger State 3.
• State 3 – “Stopping Motor”. Stop the DC motor. Trigger State 4.
• State 4 – “Time Delay 1”. Cause a time delay. Trigger State 5.
• State 5 – “Back Away”. Turns the DC motor backwards for 5 second. Motors may run at unequal speeds to cause a reverse turn if desired. Trigger State 6.
• State 6- “Time Delay 2”. Cause a time delay. Trigger State 1.
The program should run through the States as defined in a repeating loop.
Explanation / Answer
enum states
{
State_1,
State_2,
State_3,
State_4,
State_5,
State_6,
};
//
enum states motor_state; // this is the state variable used to control the motor state transition
//
// Funtion runs the DC motor continuously forward
void runForward()
{
printf("Running Forward "); // dummy line, replace with actual code
// to be implemented
}
//
// Function reads a sensor and loop in a while loop till an object has been detected with 10cms
int waitForSensor()
{
//
int sensorObjectDetected = 0;
//
// loop continuously till an object has been detected
while(!sensorObjectDetected)
{
// read sensor data and compare for detection
break;
}
//
return 0;
}
//
// function drives dc motor in reverse motion
void reverseMotor()
{
// to be implemented,
}
//
// function stops a dc motor
void stopMotor()
{
// to be implemented
}
void setup() {
// put your setup code here, to run once:
motor_state = State_1; // intialise the motor in State_1
}
void loop() {
// put your main code here, to run repeatedly:
switch(motor_state)
{
// motor_state = 0 => state 1
case State_1:
//
runForward(); // run the DC forward in state 1
//
motor_state = State_2; // trigger state 2
//
break;
//
// motor_state = 1 => state 2
case State_2:
//
waitForSensor(); // wait till the sensor detects an object and returns
//
motor_state = State_3; // trigger state 3
//
break;
//
case State_3:
//
stopMotor(); // stop the motor
//
motor_state = State_4; // trigger state 4
//
break;
//
case State_4:
//
delay(1000); // 1s delay
//
motor_state = State_5; // trigger state 5
//
break;
//
case State_5:
//
reverseMotor();
//
delay(5000); // reverse the motor for 5s
//
motor_state = State_6;
//
break;
//
case State_6:
//
delay(2000); // delay of 2s
//
motor_state = State_1;
//
break;
}
}
// NOTE : Motor functions to be implemented by student
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.