Certainly! To implement a structured parking maneuver with four distinct steps, it's best to use a state machine approach. This method allows your program to transition between different states (steps) based on specific conditions, making the logic clear and maintainable.
Below, I'll guide you through modifying your existing loop() function to incorporate the four steps:
- Turn Right and Move Backwards
- Straighten Out and Move Backwards, Verify Position
- Turn Right and Move Forwards
- Straighten Out and Move Forwards, Verify Position
We'll introduce a ParkingState enum to manage these states and update the logic accordingly.
Step 1: Define the Parking States
First, define an enumeration to represent the different states of the parking maneuver.
// Define Parking States
enum ParkingState {
IDLE,
TURN_RIGHT_BACKWARD,
STRAIGHTEN_BACKWARD,
TURN_RIGHT_FORWARD,
STRAIGHTEN_FORWARD,
PARKING_COMPLETE
};
// Initialize current state
ParkingState currentState = IDLE;
Step 2: Modify the loop() Function
Update your loop() function to handle different states based on the currentState. Here's how you can structure it:
void loop() {
switch (currentState) {
case IDLE:
// Wait until the front wall is detected
if (detectColorWall()) {
Serial.println("Front Wall Detected. Initiating Parking Maneuver.");
resetYawIntegration(); // Reset yaw before starting
initialYaw = integratedYaw;
currentState = TURN_RIGHT_BACKWARD;
}
break;
case TURN_RIGHT_BACKWARD:
Serial.println("State: TURN_RIGHT_BACKWARD");
turnSteering(SERVO_RIGHT);
moveBackward(150); // Adjust speed as needed
startTime = millis();
while (true) {
float deltaYaw = readYaw();
Serial.print("Delta Yaw: ");
Serial.println(deltaYaw);
float yawChange = abs(integratedYaw - initialYaw);
float backDistance = readUltrasonic(BACK_TRIG_PIN, BACK_ECHO_PIN);
bool backWallDetected = detectColorWall();
if (yawChange >= YAW_THRESHOLD || (backDistance != -1.0 && backDistance <= MIN_DISTANCE) || backWallDetected) {
Serial.println("Stopping Backward Movement after Turning Right.");
stopMotors();
currentState = STRAIGHTEN_BACKWARD;
break;
}
if (millis() - startTime > TIMEOUT) {
Serial.println("Timeout Reached during Turning Right Backward.");
stopMotors();
currentState = IDLE; // Optionally retry or handle error
break;
}
}
break;
case STRAIGHTEN_BACKWARD:
Serial.println("State: STRAIGHTEN_BACKWARD");
float straighteningInitialYaw = integratedYaw;
turnSteering(SERVO_LEFT);
startTime = millis();
while (true) {
moveBackward(150); // Adjust speed as needed
float deltaYaw = readYaw();
Serial.print("Delta Yaw during Straightening: ");
Serial.println(deltaYaw);
float yawChange = abs(integratedYaw - straighteningInitialYaw);
float backDistance = readUltrasonic(BACK_TRIG_PIN, BACK_ECHO_PIN);
bool backWallDetected = detectColorWall();
// Proportional Steering Adjustment
if (yawChange < YAW_THRESHOLD) {
int steeringAdjustment = map(yawChange * 10, 0, YAW_THRESHOLD * 10, SERVO_LEFT, 90); // Multiply to maintain resolution
steeringAdjustment = constrain(steeringAdjustment, SERVO_LEFT, 90);
turnSteering(steeringAdjustment);
} else {
turnSteering(SERVO_LEFT);
}
if (yawChange >= YAW_THRESHOLD || (backDistance != -1.0 && backDistance <= MIN_DISTANCE) || backWallDetected) {
Serial.println("Straightening Complete.");
stopMotors();
currentState = TURN_RIGHT_FORWARD;
break;
}
if (millis() - startTime > TIMEOUT) {
Serial.println("Timeout Reached during Straightening Backward.");
stopMotors();
currentState = IDLE; // Optionally retry or handle error
break;
}
}
break;
case TURN_RIGHT_FORWARD:
Serial.println("State: TURN_RIGHT_FORWARD");
turnSteering(SERVO_RIGHT);
moveForward(150); // Adjust speed as needed
startTime = millis();
while (true) {
float deltaYaw = readYaw();
Serial.print("Delta Yaw: ");
Serial.println(deltaYaw);
float yawChange = abs(integratedYaw - initialYaw);
float frontDistance = readUltrasonic(FRONT_TRIG_PIN, FRONT_ECHO_PIN);
bool frontWallDetected = detectColorWall();
if (yawChange >= YAW_THRESHOLD || (frontDistance != -1.0 && frontDistance <= MIN_DISTANCE) || frontWallDetected) {
Serial.println("Stopping Forward Movement after Turning Right.");
stopMotors();
currentState = STRAIGHTEN_FORWARD;
break;
}
if (millis() - startTime > TIMEOUT) {
Serial.println("Timeout Reached during Turning Right Forward.");
stopMotors();
currentState = IDLE; // Optionally retry or handle error
break;
}
}
break;
case STRAIGHTEN_FORWARD:
Serial.println("State: STRAIGHTEN_FORWARD");
float straightenForwardInitialYaw = integratedYaw;
turnSteering(SERVO_LEFT);
startTime = millis();
while (true) {
moveForward(150); // Adjust speed as needed
float deltaYaw = readYaw();
Serial.print("Delta Yaw during Straightening Forward: ");
Serial.println(deltaYaw);
float yawChange = abs(integratedYaw - straightenForwardInitialYaw);
float frontDistance = readUltrasonic(FRONT_TRIG_PIN, FRONT_ECHO_PIN);
bool frontWallDetected = detectColorWall();
// Proportional Steering Adjustment
if (yawChange < YAW_THRESHOLD) {
int steeringAdjustment = map(yawChange * 10, 0, YAW_THRESHOLD * 10, SERVO_LEFT, 90);
steeringAdjustment = constrain(steeringAdjustment, SERVO_LEFT, 90);
turnSteering(steeringAdjustment);
} else {
turnSteering(SERVO_LEFT);
}
if (yawChange >= YAW_THRESHOLD || (frontDistance != -1.0 && frontDistance <= MIN_DISTANCE) || frontWallDetected) {
Serial.println("Straightening Forward Complete.");
stopMotors();
// Proceed to verify position
if (verifyPosition()) {
Serial.println("Parking Successful!");
currentState = PARKING_COMPLETE;
} else {
Serial.println("Position Verification Failed. Adjusting...");
currentState = IDLE; // Optionally implement further adjustment steps
}
break;
}
if (millis() - startTime > TIMEOUT) {
Serial.println("Timeout Reached during Straightening Forward.");
stopMotors();
currentState = IDLE; // Optionally retry or handle error
break;
}
}
break;
case PARKING_COMPLETE:
Serial.println("State: PARKING_COMPLETE");
stopMotors();
Serial.println("Parking Complete and Motors Stopped.");
while (1) {
// Halt the program
delay(1000);
}
break;
default:
// Handle unexpected states
Serial.println("Unknown State. Resetting to IDLE.");
currentState = IDLE;
break;
}
}
Step 3: Explanation of the State Machine
-
IDLE State:
- The system waits until the front wall is detected using the color sensor.
- Once detected, it transitions to the
TURN_RIGHT_BACKWARD state.
-
TURN_RIGHT_BACKWARD State:
- The steering is turned to the maximum right (
SERVO_RIGHT).
- The robot starts moving backward.
- It continues until either:
- The yaw changes exceed the threshold.
- The back ultrasonic sensor detects an object within the minimum distance.
- A wall is detected by the color sensor.
- Upon stopping, it transitions to the
STRAIGHTEN_BACKWARD state.
-
STRAIGHTEN_BACKWARD State:
- The steering is turned to the maximum left (
SERVO_LEFT) to straighten out.
- The robot continues moving backward.
- It adjusts the steering proportionally based on the yaw change.
- It stops either upon meeting the yaw threshold, detecting an object, or timeout.
- Transitions to the
TURN_RIGHT_FORWARD state.
-
TURN_RIGHT_FORWARD State:
- Similar to the first turn but in the forward direction.
- The steering is turned to the maximum right (
SERVO_RIGHT).
- The robot starts moving forward.
- It stops based on the same conditions and transitions to the
STRAIGHTEN_FORWARD state.
-
STRAIGHTEN_FORWARD State:
- The steering is adjusted back to the maximum left (
SERVO_LEFT) to straighten.
- The robot moves forward and adjusts steering proportionally.
- Upon completion, it verifies the parking position.
- If successful, transitions to
PARKING_COMPLETE; otherwise, resets to IDLE for potential adjustments.
-
PARKING_COMPLETE State:
- All motors are stopped.
- The program halts, indicating successful parking.
Step 4: Additional Considerations
-
Debouncing Sensor Readings:
- Ensure that sensor readings are stable before making decisions. You might want to add additional checks or averaging of sensor values to prevent false triggers.
-
Calibration:
- Color Sensor: The frequency ranges for detecting colors (e.g., pink) need to be calibrated based on your specific wall color and lighting conditions.
- Gyroscope: Ensure that the yaw integration is accurate. Consider implementing drift correction techniques or using complementary sensors like magnetometers for more accurate orientation.
-
Timeout Handling:
- Currently, if a timeout occurs, the system resets to
IDLE. Depending on your application's needs, you might want to implement retries or error handling mechanisms.
-
Proportional Steering Adjustment:
- The
map function scales the yaw change to the steering angle. Adjust the scaling factor (* 10 in the example) to suit the responsiveness of your steering servo.
-
Non-Blocking Code:
- The current implementation uses
while (true) loops within states, which can block the main loop. For a more responsive system, consider refactoring to use non-blocking logic with state transitions handled within the main loop without nested loops.
Step 5: Refactoring for Non-Blocking Behavior (Optional but Recommended)
Using blocking while loops can make the system unresponsive to new sensor inputs or commands. Here's how you can restructure the state machine to avoid blocking:
-
Track State Entry Time:
- Use variables to track when a state was entered to manage timeouts.
-
Handle State Actions Incrementally:
- Perform small actions in each loop iteration and transition states based on conditions.
Example Refactored State Machine:
// Additional Variables
unsigned long stateStartTime = 0;
float stateInitialYaw = 0.0;
void loop() {
unsigned long currentMillis = millis();
switch (currentState) {
case IDLE:
if (detectColorWall()) {
Serial.println("Front Wall Detected. Initiating Parking Maneuver.");
resetYawIntegration();
initialYaw = integratedYaw;
stateStartTime = currentMillis;
currentState = TURN_RIGHT_BACKWARD;
}
break;
case TURN_RIGHT_BACKWARD:
if (stateStartTime == 0) {
turnSteering(SERVO_RIGHT);
moveBackward(150);
stateInitialYaw = integratedYaw;
stateStartTime = currentMillis;
}
// Check conditions
float yawChange1 = abs(integratedYaw - stateInitialYaw);
float backDistance1 = readUltrasonic(BACK_TRIG_PIN, BACK_ECHO_PIN);
bool backWallDetected1 = detectColorWall();
if (yawChange1 >= YAW_THRESHOLD || (backDistance1 != -1.0 && backDistance1 <= MIN_DISTANCE) || backWallDetected1) {
stopMotors();
currentState = STRAIGHTEN_BACKWARD;
stateStartTime = currentMillis;
} else if (currentMillis - stateStartTime > TIMEOUT) {
Serial.println("Timeout during TURN_RIGHT_BACKWARD.");
stopMotors();
currentState = IDLE;
}
break;
// Implement other states similarly without blocking loops...
case PARKING_COMPLETE:
stopMotors();
Serial.println("Parking Complete and Motors Stopped.");
while (1) { delay(1000); }
break;
default:
Serial.println("Unknown State. Resetting to IDLE.");
currentState = IDLE;
break;
}
// Add a small delay to prevent overwhelming the loop
delay(10);
}
Note: Implementing a non-blocking state machine requires careful management of state transitions and actions. The above example shows the initial structure for TURN_RIGHT_BACKWARD. You would need to similarly implement the remaining states (STRAIGHTEN_BACKWARD, TURN_RIGHT_FORWARD, STRAIGHTEN_FORWARD) in a non-blocking manner.
Final Thoughts
Implementing a state machine enhances the organization and readability of your code, especially for complex sequences like parking maneuvers. Ensure that all sensor readings are reliable and that actuator commands (like motor speeds and steering angles) are calibrated for your specific hardware setup.
Feel free to adjust the state transitions, conditions, and actions based on the real-world performance and requirements of your robot. Testing each state individually can help in fine-tuning the behavior before deploying the complete parking sequence.
If you encounter specific issues or need further assistance with particular parts of the implementation, feel free to ask!