Okay, let's outline the code logic for path planning in a line follower robot, focusing on the common PID (Proportional-Integral-Derivative) control method. This logic can be adapted for various platforms like Arduino, Raspberry Pi, ESP32, etc., using their respective programming languages (C++, Python).
We'll use pseudocode for clarity, assuming a differential drive robot (two independently controlled wheels) and an array of sensors (e.g., 5 IR reflectance sensors).
// --- Constants ---
// PID Gains (These MUST be tuned for your specific robot and track!)
DEFINE Kp = 1.0 // Proportional gain
DEFINE Ki = 0.1 // Integral gain
DEFINE Kd = 0.5 // Derivative gain
// Motor Control
DEFINE MAX_MOTOR_SPEED = 255 // Example max speed (e.g., for Arduino PWM)
DEFINE BASE_MOTOR_SPEED = 150 // Base speed when going straight
// Sensor Configuration
DEFINE NUM_SENSORS = 5
DEFINE SENSOR_THRESHOLD = 500 // Example threshold to distinguish line from background (depends on sensor readings)
// Sensor weights (center is 0, adjust if needed)
DEFINE SENSOR_WEIGHTS = [-2, -1, 0, 1, 2] // Or [-4, -2, 0, 2, 4], etc.
// --- Variables ---
VARIABLE integralSum = 0.0
VARIABLE previousError = 0.0
VARIABLE sensorValues[NUM_SENSORS]
VARIABLE error = 0.0
VARIABLE pidCorrection = 0.0
VARIABLE leftMotorSpeed = 0
VARIABLE rightMotorSpeed = 0
// --- Setup Function (Run once at the start) ---
FUNCTION setup():
InitializeSensors() // Configure sensor pins
InitializeMotors() // Configure motor control pins (PWM, direction)
// Optional: Calibrate sensors (find min/max readings on white/black)
PRINT "Setup complete. Starting main loop..."
END FUNCTION
// --- Main Loop Function (Runs continuously) ---
FUNCTION loop():
// 1. Read Sensor Values
readSensors(sensorValues) // Function to read all sensors into the array
// 2. Calculate Error (Robot's position relative to the line)
error = calculateError(sensorValues)
// Handle case where the line is lost (all sensors read background)
IF lineIsLost(sensorValues):
// Strategy: Keep going with the last known correction, or stop, or search
// Simple approach: Use previous error to maintain direction briefly
error = previousError
// More complex: Implement a line search pattern
PRINT "Line lost! Using previous error."
// 3. Calculate PID Correction
pidCorrection = calculatePID(error)
// 4. Determine Motor Speeds
leftMotorSpeed = BASE_MOTOR_SPEED + pidCorrection
rightMotorSpeed = BASE_MOTOR_SPEED - pidCorrection
// 5. Constrain Motor Speeds (Prevent exceeding limits)
leftMotorSpeed = constrain(leftMotorSpeed, -MAX_MOTOR_SPEED, MAX_MOTOR_SPEED)
rightMotorSpeed = constrain(rightMotorSpeed, -MAX_MOTOR_SPEED, MAX_MOTOR_SPEED)
// Note: If speeds can only be positive (0 to MAX), adjust logic:
// leftMotorSpeed = constrain(leftMotorSpeed, 0, MAX_MOTOR_SPEED)
// rightMotorSpeed = constrain(rightMotorSpeed, 0, MAX_MOTOR_SPEED)
// 6. Control Motors
setMotorSpeed(LEFT_MOTOR, leftMotorSpeed)
setMotorSpeed(RIGHT_MOTOR, rightMotorSpeed)
// 7. Update state for next iteration
previousError = error
// Optional: Add a small delay to control loop frequency
delay(10) // milliseconds
END FUNCTION
// --- Helper Function: Read Sensors ---
FUNCTION readSensors(values_array):
FOR i FROM 0 TO NUM_SENSORS - 1:
values_array[i] = readAnalogSensor(i) // Or readDigitalSensor(i)
END FOR
// Optional: Apply calibration/normalization here if needed
END FUNCTION
// --- Helper Function: Calculate Error (Weighted Average Method) ---
FUNCTION calculateError(values_array):
weightedSum = 0.0
numberOfActiveSensors = 0
localError = 0.0
FOR i FROM 0 TO NUM_SENSORS - 1:
// Assuming LOWER values mean line detected (dark line, high absorption/low reflection)
IF values_array[i] < SENSOR_THRESHOLD:
weightedSum = weightedSum + (values_array[i] * SENSOR_WEIGHTS[i]) // Could also just use 1 * SENSOR_WEIGHTS[i]
numberOfActiveSensors = numberOfActiveSensors + 1 // Or use values_array[i] if it's proportional
END IF
// If HIGHER values mean line detected (e.g., light line on dark surface), change comparison to >
END FOR
IF numberOfActiveSensors > 0:
// Calculate the weighted average position
// Normalize the sum by the number of active sensors or total value sum if using raw values
localError = weightedSum / numberOfActiveSensors // Or weightedSum / totalValueSum
ELSE:
// No sensors detect the line
// Option 1: Return previous error (handled in main loop)
// Option 2: Return extreme error based on last known position
IF previousError < 0:
localError = SENSOR_WEIGHTS[0] * 1.5 // Max left error (arbitrary scaling)
ELSE:
localError = SENSOR_WEIGHTS[NUM_SENSORS - 1] * 1.5 // Max right error
// Option 3: Return 0 (go straight - risky if line truly lost)
// localError = 0
END IF
RETURN localError // Error: negative=too right, positive=too left, 0=center
END FUNCTION
// --- Helper Function: Check if Line is Lost ---
FUNCTION lineIsLost(values_array):
FOR i FROM 0 TO NUM_SENSORS - 1:
IF values_array[i] < SENSOR_THRESHOLD:
RETURN FALSE // Found the line
END IF
END FOR
RETURN TRUE // No sensor is below threshold
END FUNCTION
// --- Helper Function: Calculate PID Correction ---
FUNCTION calculatePID(currentError):
// Proportional Term
pTerm = Kp * currentError
// Integral Term (Accumulate error over time)
integralSum = integralSum + currentError
// Optional: Implement Integral Windup prevention (clamp integralSum)
integralSum = constrain(integralSum, -INTEGRAL_LIMIT, INTEGRAL_LIMIT) // Define INTEGRAL_LIMIT
iTerm = Ki * integralSum
// Derivative Term (Rate of change of error)
derivative = currentError - previousError
dTerm = Kd * derivative
// Total PID Correction
correction = pTerm + iTerm + dTerm
RETURN correction
END FUNCTION
// --- Helper Function: Set Motor Speed ---
FUNCTION setMotorSpeed(motorIdentifier, speed):
// This function contains hardware-specific code
// to set direction and PWM duty cycle for the specified motor.
// It needs to handle positive/negative speed for direction if applicable.
IF motorIdentifier == LEFT_MOTOR:
// Set left motor speed/direction
HardwareSetLeftMotor(speed)
ELSE IF motorIdentifier == RIGHT_MOTOR:
// Set right motor speed/direction
HardwareSetRightMotor(speed)
END IF
END FUNCTION
// --- Helper Function: Constrain Value ---
FUNCTION constrain(value, minVal, maxVal):
IF value < minVal:
RETURN minVal
ELSE IF value > maxVal:
RETURN maxVal
ELSE:
RETURN value
END IF
END FUNCTION
// --- Placeholder Hardware Functions (Replace with actual code) ---
FUNCTION InitializeSensors(): PRINT "Initializing Sensors..."
FUNCTION InitializeMotors(): PRINT "Initializing Motors..."
FUNCTION readAnalogSensor(index): RETURN 0 // Replace with actual analogRead()
FUNCTION HardwareSetLeftMotor(speed): PRINT "Set Left Motor:", speed
FUNCTION HardwareSetRightMotor(speed): PRINT "Set Right Motor:", speed
// --- Start Execution ---
setup()
WHILE TRUE: // Or while condition is met
loop()
END WHILE