Modularizing your Arduino code enhances readability, maintainability, and scalability. By breaking down the code into smaller, manageable functions and organizing related functionalities, you can efficiently manage each component of your system. Below is the refactored version of your code with improved modularization, along with explanations for each module.
Refactored Code
#include <Servo.h>
// #include <PID_v1.h> // Uncomment if using PID library
// Include other necessary libraries for sensors and gyro
// -------------------------------
// Enumerations and Definitions
// -------------------------------
// Define FSM states
enum State {
STATE_1,
STATE_2,
STATE_3,
STATE_4,
STATE_5,
STATE_6,
STATE_7
};
// Constants
const int D = 20; // Example threshold distance in cm
const int D1 = 30; // Another threshold distance in cm
const int X = 25; // Side threshold distance in cm
// -------------------------------
// Global Variables
// -------------------------------
State currentState = STATE_1;
// Define sensor pins
const int leftUltrasonicTrig = 2;
const int leftUltrasonicEcho = 3;
const int rightUltrasonicTrig = 4;
const int rightUltrasonicEcho = 5;
const int frontUltrasonicTrig = 6;
const int frontUltrasonicEcho = 7;
// Define motor pins
const int motorSpeedPin = 9; // PWM pin for speed control
const int motorDirPin1 = 10; // Direction pin 1
const int motorDirPin2 = 11; // Direction pin 2
// Define servo pin
const int servoPin = 12;
Servo steeringServo;
// PID variables (optional)
double Kp = 1.0, Ki = 0.0, Kd = 0.0;
double input, output, setpoint;
// PID myPID(&input, &output, &setpoint, Kp, Ki, Kd, DIRECT);
// Sensor and Control Variables
long leftDistance = 0;
long rightDistance = 0;
long frontDistance = 0;
int steeringAngle = 120; // Default neutral angle
int motorSpeed = 0;
char incomingByte;
bool objDetected = false;
int counter = 0;
// Gyro variables
float currentHeading = 0.0;
float targetHeading = 0.0;
// Timing for movements
unsigned long backStartTime = 0;
const unsigned long backDuration = 500; // 500 ms
// -------------------------------
// Function Prototypes
// -------------------------------
// Initialization Functions
void initializeHardware();
void initializeSensors();
void initializeMotors();
void initializeServo();
void initializeSerial();
void initializeGyro();
void initializePID();
// Sensor Reading Functions
long readUltrasonicDistance(int trigPin, int echoPin);
float readGyro();
void updateSensorReadings();
// Motor Control Functions
void moveMotor(int speed, bool forward);
void stopMotor();
// Servo Control Functions
void setSteeringAngle(int angle);
// State Machine Functions
void handleState1();
void handleState2();
void handleState3();
void handleState4();
void handleState5();
void handleState6();
void handleState7();
void processSerialInput();
// Utility Functions
bool isIntercept(int steeringAngle);
void takeUTurn();
void adjustSteeringWithPID();
// -------------------------------
// Setup Function
// -------------------------------
void setup() {
initializeHardware();
// Initialize PID if needed
// setpoint = 0;
// myPID.SetMode(AUTOMATIC);
}
// -------------------------------
// Loop Function
// -------------------------------
void loop() {
updateSensorReadings();
readGyro();
processSerialInput();
// State Machine Implementation
switch (currentState) {
case STATE_1:
handleState1();
break;
case STATE_2:
handleState2();
break;
case STATE_3:
handleState3();
break;
case STATE_4:
handleState4();
break;
case STATE_5:
handleState5();
break;
case STATE_6:
handleState6();
break;
case STATE_7:
handleState7();
break;
default:
currentState = STATE_1;
break;
}
}
// -------------------------------
// Initialization Implementations
// -------------------------------
void initializeHardware() {
initializeSerial();
initializeServo();
initializeMotors();
initializeSensors();
initializeGyro();
initializePID();
}
void initializeSerial() {
Serial.begin(9600);
}
void initializeServo() {
steeringServo.attach(servoPin);
setSteeringAngle(steeringAngle); // Set to neutral position
}
void initializeMotors() {
pinMode(motorSpeedPin, OUTPUT);
pinMode(motorDirPin1, OUTPUT);
pinMode(motorDirPin2, OUTPUT);
stopMotor(); // Ensure motors are stopped initially
}
void initializeSensors() {
// Initialize Ultrasonic Pins
pinMode(leftUltrasonicTrig, OUTPUT);
pinMode(leftUltrasonicEcho, INPUT);
pinMode(rightUltrasonicTrig, OUTPUT);
pinMode(rightUltrasonicEcho, INPUT);
pinMode(frontUltrasonicTrig, OUTPUT);
pinMode(frontUltrasonicEcho, INPUT);
}
void initializeGyro() {
// Initialize your gyro/magnetometer here
// Example: Gyro.begin();
}
void initializePID() {
// Initialize PID if using
// myPID.SetTunings(Kp, Ki, Kd);
}
// -------------------------------
// Sensor Reading Implementations
// -------------------------------
long readUltrasonicDistance(int trigPin, int echoPin) {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH, 30000); // Timeout after ~30ms
distance = duration * 0.034 / 2; // Convert to cm
return distance;
}
float readGyro() {
// Implement gyro reading based on your gyro library
// Example:
// return Gyro.getHeading();
return 0.0; // Placeholder
}
void updateSensorReadings() {
leftDistance = readUltrasonicDistance(leftUltrasonicTrig, leftUltrasonicEcho);
rightDistance = readUltrasonicDistance(rightUltrasonicTrig, rightUltrasonicEcho);
frontDistance = readUltrasonicDistance(frontUltrasonicTrig, frontUltrasonicEcho);
}
// -------------------------------
// Motor Control Implementations
// -------------------------------
void moveMotor(int speed, bool forward) {
analogWrite(motorSpeedPin, speed);
if (forward) {
digitalWrite(motorDirPin1, HIGH);
digitalWrite(motorDirPin2, LOW);
} else {
digitalWrite(motorDirPin1, LOW);
digitalWrite(motorDirPin2, HIGH);
}
}
void stopMotor() {
analogWrite(motorSpeedPin, 0);
digitalWrite(motorDirPin1, LOW);
digitalWrite(motorDirPin2, LOW);
}
// -------------------------------
// Servo Control Implementations
// -------------------------------
void setSteeringAngle(int angle) {
steeringServo.write(angle);
steeringAngle = angle;
}
// -------------------------------
// Serial Processing Implementation
// -------------------------------
void processSerialInput() {
if (Serial.available() > 0) {
incomingByte = Serial.read();
if (currentState == STATE_1 && incomingByte == 'n') {
objDetected = false;
} else if (incomingByte == 'd') {
objDetected = true;
// Read subsequent characters for angle
String angleStr = "";
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') break; // Assuming angle sent ends with newline
angleStr += c;
}
steeringAngle = angleStr.toInt();
setSteeringAngle(steeringAngle);
} else if (incomingByte == 'i') {
// Signal 'i' received indicating ideal position reached
// Handle in relevant state
}
}
}
// -------------------------------
// State Machine Implementations
// -------------------------------
void handleState1() {
// Conditions:
// Left and Right distances < D
// Front distance > D1
// No obstacle detected (serial 'n')
if (leftDistance < D && rightDistance < D && frontDistance > D1 && !objDetected) {
setSteeringAngle(120);
motorSpeed = 180;
moveMotor(motorSpeed, true);
// PID Control to center
adjustSteeringWithPID();
// Transition: Remain in STATE_1 until conditions change
if (objDetected) {
currentState = STATE_2;
}
}
}
void handleState2() {
// Conditions:
// Left and Right distances < D
// Object detected
if (leftDistance < D && rightDistance < D && objDetected) {
// Set steering angle based on serial input
setSteeringAngle(steeringAngle);
motorSpeed = 150;
moveMotor(motorSpeed, true);
// Wait until 'i' signal is received
if (incomingByte == 'i') {
counter++;
currentState = STATE_3;
}
}
}
void handleState3() {
// Conditions:
// Left distance > X
// Front distance < D1
// Right distance < D
// No obstacle detected
if (leftDistance > X && frontDistance < D1 && rightDistance < D && !objDetected) {
setSteeringAngle(70); // 120 - 50 degrees
motorSpeed = 150;
moveMotor(motorSpeed, true);
// Set target heading
targetHeading = currentHeading + 42; // Assuming 42 degrees to the right
// Perform turning until target heading is reached
while (abs(currentHeading - targetHeading) < 42) {
currentHeading = readGyro();
// Continuously check for obstacle
if (Serial.available() > 0) {
char obstacle = Serial.read();
if (obstacle == 'd') {
// Read steering angle from serial
String angleStr = "";
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') break;
angleStr += c;
}
steeringAngle = angleStr.toInt();
setSteeringAngle(steeringAngle);
currentState = STATE_4;
break;
}
}
}
// After turning
currentState = STATE_5;
}
}
void handleState4() {
// Call isIntercept with current steering angle
if (isIntercept(steeringAngle)) {
// Move backward at speed 130 for 500 ms
moveMotor(130, false);
delay(backDuration);
stopMotor();
// Re-evaluate interception
if (isIntercept(steeringAngle)) {
// Repeat
backStartTime = millis();
} else {
// Move forward at speed 130
moveMotor(130, true);
currentState = STATE_5;
}
} else {
// Move forward at speed 130
moveMotor(130, true);
currentState = STATE_5;
}
}
void handleState5() {
// Transition after State 3 Actions
if (objDetected) {
currentState = STATE_2;
} else {
currentState = STATE_1;
}
// Reset steering to neutral
setSteeringAngle(120);
}
void handleState6() {
// Similar to STATE_3 but for right-side conditions
// Conditions:
// Right distance > X
// Front distance < D1
// Left distance < D
// No obstacle detected
if (rightDistance > X && frontDistance < D1 && leftDistance < D && !objDetected) {
setSteeringAngle(170); // 120 + 50 degrees
motorSpeed = 150;
moveMotor(motorSpeed, true);
// Set target heading
targetHeading = currentHeading - 42; // Assuming 42 degrees to the left
// Perform turning until target heading is reached
while (abs(currentHeading - targetHeading) < 42) {
currentHeading = readGyro();
// Continuously check for obstacle
if (Serial.available() > 0) {
char obstacle = Serial.read();
if (obstacle == 'd') {
// Read steering angle from serial
String angleStr = "";
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') break;
angleStr += c;
}
steeringAngle = angleStr.toInt();
setSteeringAngle(steeringAngle);
currentState = STATE_4;
break;
}
}
}
// After turning
currentState = STATE_5;
}
}
void handleState7() {
// If counter > 7, handle U-turn when next object is detected
if (counter > 7 && objDetected) {
// Check if green signal from RPI (Assuming 'g' represents green)
if (incomingByte == 'g') {
currentState = STATE_2;
} else {
takeUTurn();
// Reset counter after U-turn
counter = 0;
}
}
}
// -------------------------------
// Utility Function Implementations
// -------------------------------
bool isIntercept(int steeringAngle) {
// Implement interception logic based on steering angle
// Return true if intercept occurs, else false
// For example purposes, return false
return false;
}
void takeUTurn() {
// Implement U-turn logic
// For example, turn servo to 180 deg, move forward, etc.
setSteeringAngle(180);
moveMotor(150, true);
delay(1000); // Move forward for 1 second
setSteeringAngle(60); // Reverse steering
delay(1000); // Turn for 1 second
setSteeringAngle(120); // Return to neutral
stopMotor();
currentState = STATE_1;
}
void adjustSteeringWithPID() {
// Implement PID adjustment if using PID
/*
double pidError = leftDistance - rightDistance;
input = pidError;
myPID.Compute();
setSteeringAngle(steeringAngle + (int)output);
*/
// Placeholder for PID adjustment
}
// -------------------------------
// Additional Notes
// -------------------------------
/*
1. **State Handlers:** Each state has its own handler function (`handleState1()`, `handleState2()`, etc.), which encapsulates the logic specific to that state. This makes the main loop cleaner and each state easier to manage.
2. **Initialization Functions:** Hardware initialization is separated into distinct functions, enhancing clarity and making it easier to modify or debug specific components.
3. **Sensor and Control Functions:** Sensor reading, motor control, and servo control are modularized into their respective functions, promoting reusability.
4. **Serial Processing:** Handling serial input is encapsulated in `processSerialInput()`, ensuring that serial communication logic is isolated from the main state machine.
5. **Utility Functions:** Functions like `isIntercept()` and `takeUTurn()` handle specific behaviors, keeping the state handlers concise.
6. **Comments and Documentation:** Clear comments are added to explain the purpose of each function and section, aiding future maintenance and collaboration.
7. **Constants for Thresholds:** Threshold distances (`D`, `D1`, `X`) are defined as constants at the beginning, making it easy to adjust sensor sensitivities.
8. **Placeholder Implementations:** Functions like `readGyro()` and `isIntercept()` are placeholders and should be implemented based on your specific hardware and requirements.
9. **PID Control:** If you decide to use PID control, ensure you properly initialize and incorporate it within your steering logic.
10. **Error Handling:** Consider adding error handling mechanisms, especially for sensor readings and critical operations, to make your system more robust.
*/
Explanation of Modularization
-
Enumerations and Definitions:
- Enumerations like
State define the various states of the Finite State Machine (FSM).
- Constants such as
D, D1, and X are defined for threshold distances, making it easy to adjust them as needed.
-
Global Variables:
- Variables are grouped based on their functionality, such as sensor readings, motor control, servo control, and gyro data.
-
Function Prototypes:
- Clear prototypes are declared for initialization, sensor reading, motor control, servo control, state handling, and utility functions.
-
Initialization Functions:
initializeHardware(): Calls all other initialization functions to set up the hardware components.
initializeSerial(), initializeServo(), initializeMotors(), initializeSensors(), initializeGyro(), initializePID(): Each function initializes a specific component, keeping the setup organized.
-
Sensor Reading Functions:
readUltrasonicDistance(): Reads distance from ultrasonic sensors.
readGyro(): Placeholder for reading gyro data.
updateSensorReadings(): Updates all sensor readings, keeping sensor logic centralized.
-
Motor Control Functions:
moveMotor(): Controls motor speed and direction.
stopMotor(): Stops the motor immediately.
-
Servo Control Functions:
setSteeringAngle(): Sets the steering servo to a specified angle and updates the steeringAngle variable.
-
Serial Processing Implementation:
processSerialInput(): Handles incoming serial data, parsing commands and updating relevant variables. This ensures that serial communication logic doesn't clutter the main loop or state handlers.
Additional Recommendations
By following this modular approach, your code becomes more organized, easier to understand, and simpler to maintain or extend in the future.