// Tolerance for Matching Distances (in cm)
const double DISTANCE_TOLERANCE = 15.
// Motor Pins
const int IN1 = 4;
const int IN2 = 3;
const int ENA = 5;
// Ultrasonic Sensor Pins
const int TRIG_FRONT = 46;
const int ECHO_FRONT = 47;
const int TRIG_LEFT = 9;
const int ECHO_LEFT = 8;
const int TRIG_RIGHT = 12;
const int ECHO_RIGHT = 11;
// LED Indicator Pin
const int LED_PIN = 13;
// --------------------- Global Variables --------------------- //
// Servo Control
Servo servo;
int pos = 90; // Start at standard steering angle
Serial.print("Front Distance: ");
Serial.print(frontDistance);
Serial.print(" cm, Left Distance: ");
Serial.print(leftDistance);
Serial.print(" cm, Right Distance: ");
Serial.print(rightDistance);
Serial.print(" cm, Heading: ");
Serial.print(heading);
Serial.print("°, Current State: ");
Serial.println(currentState);
// FSM Logic
switch (currentState) {
case FOLLOW_LINE:
if (frontDistance < 60) {
/**if (leftDistance < 30 && rightDistance > 80) {
currentState = TURN_RIGHT;
digitalWrite(LED_PIN, HIGH); // Optional: Indicate turning right
}
else if (leftDistance > 80 && rightDistance < 30) {
currentState = TURN_LEFT;
digitalWrite(LED_PIN, HIGH); // Optional: Indicate turning left
}*/
if(leftDistance - rightDistance > 60){
currentState = TURN_LEFT;
}
else{
currentState = TURN_RIGHT;
}}
else {
// Continue moving forward with PID steering
moveForward(160);
// Example PID usage (you might need to adjust based on your line-following mechanism)
PID_error = leftDistance - rightDistance;
steering_angle_degrees = (30 * PID_Controller(PID_error)) + std_steering_angle;
steering_angle_degrees = constrain(steering_angle_degrees, std_steering_angle - 45, std_steering_angle + 45);
turnServo(steering_angle_degrees);
}
break;
code
case TURN_LEFT:
Serial.println("Executing TURN_LEFT");
digitalWrite(LED_PIN, HIGH);
// Capture the starting heading
double startHeadingLeft = heading;
// Calculate target heading
double targetHeadingLeft = normalizeAngle(startHeadingLeft - 42.0);
// Start turning left
moveForward(150);
turnServo(std_steering_angle - 40);
// Continuously update heading until target is reached
while (!hasTurnedLeft(startHeadingLeft, heading, 35.0)) {
updateHeading();
Serial.print("Current Heading (Left Turn): ");
Serial.println(heading);
delay(50); // Small delay to prevent flooding the serial output
}
// Stop turning
turnServo(std_steering_angle);
no_of_turns++;
currentState = FOLLOW_LINE;
digitalWrite(LED_PIN, LOW);
Serial.println("TURN_LEFT Completed");
break;
case TURN_RIGHT:
Serial.println("Executing TURN_RIGHT");
digitalWrite(LED_PIN, HIGH);
// Capture the starting heading
double startHeadingRight = heading;
// Calculate target heading
double targetHeadingRight = normalizeAngle(startHeadingRight + 42.0);
// Start turning right
moveForward(150);
turnServo(std_steering_angle + 40);
// Continuously update heading until target is reached
while (!hasTurnedRight(startHeadingRight, heading, 42.0)) {
updateHeading();
Serial.print("Current Heading (Right Turn): ");
Serial.println(heading);
delay(50); // Small delay to prevent flooding the serial output
}
// Stop turning
turnServo(std_steering_angle);
no_of_turns++;
currentState = FOLLOW_LINE;
digitalWrite(LED_PIN, LOW);
Serial.println("TURN_RIGHT Completed");
break;
case RETURN_TO_START: // New State Handling
Serial.println("Executing RETURN_TO_START");
// Check if current distances are within tolerance of initial distances
if ( (abs(frontDistance - initialFrontDistance) <= DISTANCE_TOLERANCE) &&
(abs(leftDistance - initialLeftDistance) <= DISTANCE_TOLERANCE) &&
(abs(rightDistance - initialRightDistance) <= DISTANCE_TOLERANCE) ) {
Serial.println("Returned to Start Position");
currentState = STOP;
}
else {
// Navigate towards the start position
// Example Logic: Adjust steering based on difference from initial distances
double errFront = initialFrontDistance - frontDistance;
double errLeft = initialLeftDistance - leftDistance;
double errRight = initialRightDistance - rightDistance;
PID_error = (errLeft - errRight); // Example PID error
steering_angle_degrees = (30 * PID_Controller(PID_error)) + std_steering_angle;
steering_angle_degrees = constrain(steering_angle_degrees, std_steering_angle - 45, std_steering_angle + 45);
turnServo(steering_angle_degrees);
moveForward(150);
}
break;
case STOP:
Serial.println("Stopping.");
stopMotors();
while (1); // Halt the program
break;
}
// Optional: Stop after a certain number of turns
if (no_of_turns >= 12 && currentState != RETURN_TO_START && currentState != STOP) {
Serial.println("Reached 12 Turns. Initiating Return to Start.");
resetPID(); // Reset PID before starting return
currentState = RETURN_TO_START;
}
// Function to move the robot forward at a specified speed
void moveForward(int speed) {
digitalWrite(IN1, LOW);
digitalWrite(IN2, HIGH);
analogWrite(ENA, speed);
}
// Function to stop all motors
void stopMotors() {
digitalWrite(IN1, LOW);
digitalWrite(IN2, LOW);
analogWrite(ENA, 0);
}
// Function to turn the servo to a specific angle smoothly
void turnServo(int angle) {
angle = constrain(angle, 0, 180);
if (pos != angle) {
while (pos != angle) {
pos += (pos < angle) ? 1 : -1;
servo.write(pos);
delay(5);
}
}
}
// Function to read distance from an ultrasonic sensor in centimeters
long readUltrasonicDistance(int trigPin, int echoPin) {
// Clear trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Function to normalize angles between 0 and 360 degrees
double normalizeAngle(double angle) {
while (angle < 0) angle += 360;
while (angle >= 360) angle -= 360;
return angle;
}
// Function to check if the robot has turned left by the desired delta
bool hasTurnedLeft(double start, double current, double delta) {
double target = normalizeAngle(start - delta);
// Determine if the current heading has passed the target heading
// Considering wrap-around
if (start >= target) {
if (current <= target || current >= start) {
return true;
}
else {
return false;
}
}
else {
// This case shouldn't occur for left turns, but included for completeness
return current <= target;
}
}
// Function to check if the robot has turned right by the desired delta
bool hasTurnedRight(double start, double current, double delta) {
double target = normalizeAngle(start + delta);
// Determine if the current heading has passed the target heading
// Considering wrap-around
if (start <= target) {
if (current >= target || current <= start) {
return true;
}
else {
return false;
}
}
else {
// This case shouldn't occur for right turns, but included for completeness
return current >= target;
}
}
// Function to reset PID variables
void resetPID() {
sum_err = 0;
prev_err = 0;
}
now, write the same fsm in python, such that the ultrasonic readings are recieved by the rpi from arduino serially, 1st float is the front distacne, next float is left, third is right distance, stop the ultrasonic and give heading diff readings fro arduino to rpi when in a turn state. here, i want this exact exact fsm to be implemented by calling a method called open if a push button is pressed for less than 2 sec but if pressed for more than 2 sec write another method called obstacle (just leave empty for now) the motor speed and servo angles are sent to a different slave arduino, first being a motor int and then servo angle int (in a case follow line, write the standard steering angle in the message), figure a way to connect 2 slave arduinos, one for input and the other output
To implement the finite state machine (FSM) from your Arduino code in Python on a Raspberry Pi (RPi), we'll create a Python script that interfaces with two slave Arduinos:
Input Arduino: Handles sensor readings (front, left, right distances) and sends them to the RPi via serial communication.
Output Arduino: Receives motor speed and servo angle commands from the RPi via serial communication to control the robot's movement.
Additionally, we'll handle a push button to trigger specific actions based on the duration of the press.
Overview of the System Architecture
RPi runs the Python script that:
Reads sensor data from the Input Arduino.
Implements the FSM logic.
Sends motor and servo commands to the Output Arduino.
Monitors a push button to trigger open or obstacle methods.
Input Arduino continuously sends sensor data (front distance, left distance, right distance) to the RPi via a serial connection.
Output Arduino listens for motor speed and servo angle commands from the RPi and controls the motors and servo accordingly.
Hardware Connections
Input Arduino:
Connect to the RPi via a USB port (e.g., /dev/ttyUSB0).
Output Arduino:
Connect to the RPi via another USB port (e.g., /dev/ttyUSB1).
Push Button:
Connect to one of the RPi's GPIO pins (e.g., GPIO17) with appropriate pull-down resistors.
Python Implementation
Below is the comprehensive Python script that accomplishes the desired functionality. It uses the pyserial library for serial communication and RPi.GPIO for handling the push button.
Prerequisites
Install Required Libraries:
bash
pip install pyserial RPi.GPIO
Identify Serial Ports:
Determine which serial ports the Input and Output Arduinos are connected to (e.g., /dev/ttyUSB0 and /dev/ttyUSB1).
You can list connected serial devices using:
bash
ls /dev/ttyUSB*
Python Script
python
Explanation of the Python Script
Imports and Configuration:
Libraries:serial for serial communication, time for delays, threading for thread-safe operations, and RPi.GPIO for handling the push button.
Configuration Variables: Define serial ports, baud rates, GPIO pin for the button, FSM states, standard steering angles, motor speed limits, etc.
Helper Functions:
initialize_serial_ports(): Establishes serial connections with the Input and Output Arduinos.
send_commands(): Sends motor speed and servo angle commands to the Output Arduino in the format "speed,angle\n".
read_input_data(): Reads and parses incoming data from the Input Arduino. It expects either three floats (front, left, right distances) or a single float indicating heading difference during turns.
PID_Controller(): Implements a simple PID controller for steering adjustments.
normalize_angle(): Ensures the heading angle stays within [0, 360) degrees.
FSM Implementation:
follow_line(): Continuously moves the robot forward and adjusts steering based on sensor data using PID control. Transitions to turn states if an obstacle is detected.
turn_left() and turn_right(): Handles left and right turns by adjusting the servo angle and monitoring the heading to determine when the turn is complete.
has_turned_left() and has_turned_right(): Helper functions to determine if the desired turn angle has been achieved.
return_to_start(): Placeholder for logic to return the robot to its starting position after a certain number of turns.
stop_robot(): Stops all movement by sending zero speeds and standard steering angles.
Button Handling:
button_callback(): Detects button presses and releases. Determines if the press duration is short (open_method()) or long (obstacle_method()).
setup_button(): Initializes GPIO for the push button with appropriate debouncing.
Main Loop:
main_loop(): The core loop that continuously reads sensor data, updates the FSM state, and sends commands to the Output Arduino. It also checks if the maximum number of turns has been reached to initiate returning to the start position.
Notes and Considerations
Serial Communication Protocol:
Input Arduino: Should send data in a consistent format. For example:
Normal State:"front,left,right\n" (e.g., "50.0,60.0,55.0\n")
Turn State:"heading_diff\n" (e.g., "5.0\n")
Output Arduino: Should parse incoming commands as "speed,angle\n".
Push Button Wiring:
Ensure the push button is connected with appropriate pull-up or pull-down resistors to prevent false triggers. The script assumes a pull-down configuration.
Error Handling:
The script includes basic error handling for serial communication. Depending on your application, you might want to add more robust error checking and recovery mechanisms.
Adjustments and Calibration:
PID Parameters: The Kp, Ki, and Kd values might need tuning based on the robot's performance.
Steering Angles: Adjust STEERING_ANGLE_LIMIT and servo angle offsets as per your hardware setup.
Distance Tolerances: Modify distance_tolerance based on the environment and sensor accuracy.
Concurrency and Performance:
For more responsive and efficient handling, consider using threading or asynchronous programming, especially if sensor reading and command sending need to occur simultaneously without blocking.
Initial Heading:
The script currently sets the initial heading based on the first reading. Ensure that the Input Arduino provides accurate initial heading information.
Safety:
Implement fail-safes to stop the robot in case of unexpected behavior or sensor failures to prevent potential damage.
Conclusion
This Python script effectively mirrors the FSM logic from your original Arduino code, leveraging the computational power of the Raspberry Pi. By separating sensor input and motor/servo output into two Arduinos, the system ensures modularity and clarity in communication. Ensure that both Arduinos are programmed appropriately to adhere to the expected serial communication protocols for seamless integration.