Arduino Robot Car Programming: Your First Steps in Robotics

Embarking on the journey of robotics with an Arduino robot car is an exciting and rewarding experience. This guide will walk you through the fundamentals of programming your very own Arduino robot car, focusing on a simple yet effective obstacle avoidance program. Understanding the code is the first step to creating more complex and intelligent robotic systems. Let’s dive into the world of Arduino Robot Car Programming and explore the essential code that brings your car to life.

Understanding the Basic Code Structure

The provided code snippet offers a starting point for programming an Arduino robot car to navigate its environment. It utilizes an infrared (IR) sensor to detect obstacles and react accordingly. Let’s break down the code section by section to understand its functionality.

Setting up the Arduino Environment

#include <SoftwareSerial.h>
#define LEFT_A1 4
#define LEFT_B1 5
#define RIGHT_A2 6
#define RIGHT_B2 7
#define IR_TRIG 9
#define IR_ECHO 8

void setup() {
  Serial.begin(9600);
  pinMode(LEFT_A1, OUTPUT);
  pinMode(RIGHT_A2, OUTPUT);
  pinMode(LEFT_B1, OUTPUT);
  pinMode(RIGHT_B2, OUTPUT);
  pinMode(IR_TRIG, OUTPUT);
  pinMode(IR_ECHO, INPUT);
}
  • #include <SoftwareSerial.h>: This line includes the SoftwareSerial library. While not strictly necessary in this particular code as Serial communication is done via the hardware serial port, it’s often included in Arduino projects for potential future expansion or when using multiple serial devices. SoftwareSerial allows you to create serial communication on other digital pins if needed.
  • #define statements: These lines define constants for the Arduino pins connected to your robot car’s components.
    • LEFT_A1, LEFT_B1, RIGHT_A2, RIGHT_B2: These are likely connected to a motor driver module that controls the left and right motors of the robot car. By controlling these pins, we can dictate the direction and speed of each motor.
    • IR_TRIG, IR_ECHO: These pins are connected to the IR sensor. IR_TRIG (Trigger) pin will send out an infrared signal, and IR_ECHO (Echo) pin will receive the reflected signal, allowing us to measure distance.
  • void setup() { ... }: This function runs once at the beginning of your program.
    • Serial.begin(9600);: Initializes serial communication at a baud rate of 9600. This is used to send data from your Arduino to the Serial Monitor on your computer, useful for debugging and monitoring sensor readings.
    • pinMode(...): These lines configure the defined pins as either OUTPUT or INPUT. Motor control pins (LEFT_A1, LEFT_B1, RIGHT_A2, RIGHT_B2, IR_TRIG) are set as OUTPUT because the Arduino will send signals to them. The IR_ECHO pin is set as INPUT because the Arduino will receive a signal from the IR sensor.

The Main Program Loop for Obstacle Avoidance

void loop() {
  float duration, distance;
  digitalWrite(IR_TRIG, HIGH);
  delay(10);
  digitalWrite(IR_TRIG, LOW);
  duration = pulseIn(IR_ECHO, HIGH);
  distance = ((float)(340 * duration) / 10000) / 2;
  Serial.print("nDistance : ");
  Serial.println(distance);

  int sum = 0;
  while(distance < 20) {
    Serial.println("stop");
    stop();
    sum++ ;
    Serial.println(sum);
    float duration, distance;
    digitalWrite(IR_TRIG, HIGH);
    delay(10);
    digitalWrite(IR_TRIG, LOW);
    duration = pulseIn(IR_ECHO, HIGH);
    distance = ((float)(340 * duration) / 10000) / 2;
    Serial.print("nDistance : ");
    Serial.println(distance);

    if(distance >= 20){
      Serial.println("forward");
      forward();
    }
    if(distance >= 20) {
      break;
    }
    if(sum > 9) {
      Serial.println("backward");
      backward ();
      Serial.println("left");
      left ();
      Serial.println("forwardi");
      forwardi ();
      Serial.println("right");
      right ();
      Serial.println("forwardi");
      forwardi ();
      Serial.println("forwardi");
      forwardi ();
      Serial.println("right");
      right ();
      Serial.println("forwardi");
      forwardi ();
      Serial.println("left");
      left ();
      Serial.println("forward");
      forward();
      sum = 0;
    }
  }
  if(distance >= 20){
    Serial.println("forward");
    forward();
  }
}
  • void loop() { ... }: This function runs continuously in a loop after the setup() function completes. This is where the main logic of your robot car resides.
  • Distance Measurement:
    • digitalWrite(IR_TRIG, HIGH); delay(10); digitalWrite(IR_TRIG, LOW);: This sequence triggers the IR sensor to send out a pulse. A short delay is introduced to ensure the signal is sent.
    • duration = pulseIn(IR_ECHO, HIGH);: This measures the duration of the pulse received back by the IR_ECHO pin. The pulseIn() function waits for the pin to go HIGH, starts timing, waits for the pin to go LOW, and stops timing. The duration variable stores the length of this pulse in microseconds.
    • distance = ((float)(340 * duration) / 10000) / 2;: This line calculates the distance to the obstacle in centimeters. It uses the speed of sound in air (approximately 340 meters per second or 34000 cm per second). The formula converts the time duration into distance, and divides by 2 because the sound wave travels to the object and back.
    • Serial.print("nDistance : "); Serial.println(distance);: This prints the calculated distance to the Serial Monitor for debugging and monitoring.
  • Obstacle Detection and Reaction:
    • int sum = 0;: Initializes a counter variable sum.
    • while(distance < 20) { ... }: This while loop executes as long as the measured distance is less than 20 cm, indicating an obstacle is detected.
      • Serial.println("stop"); stop();: Prints “stop” to the Serial Monitor and calls the stop() function to halt the robot car.
      • sum++ ; Serial.println(sum);: Increments the sum counter and prints its value. This counter is used to implement a more complex avoidance maneuver after the robot has stopped multiple times.
      • Redundant Distance Measurement: The code inside the while loop recalculates the distance again. This is likely for continuous monitoring of the distance while the robot is attempting to avoid the obstacle.
      • if(distance >= 20){ Serial.println("forward"); forward(); }: If, after stopping and potentially maneuvering, the distance becomes greater than or equal to 20cm, the robot moves forward. This condition might be reached if the robot successfully maneuvered away from the obstacle.
      • if(distance >= 20) { break; }: This break statement exits the while loop if the distance is no longer less than 20cm.
      • Complex Avoidance Maneuver (if(sum > 9)): If the sum counter exceeds 9 (meaning the robot has stopped and encountered obstacles multiple times), it executes a sequence of movements to try to navigate around the obstacle. This sequence involves: backward, left, forward, right, forward, right, forward, left, forward. This is a pre-programmed sequence of turns and movements designed to get the robot out of a potentially cornered situation. After this maneuver, the sum counter is reset to 0.
  • Forward Movement Outside the Loop: if(distance >= 20){ Serial.println("forward"); forward();}: After the while loop (or if the distance was initially greater than or equal to 20cm), this condition is checked, and if true, the robot moves forward. This ensures that if no obstacle is detected, the robot continues moving forward.

Motor Control Functions

void forward(){
  digitalWrite(LEFT_A1, HIGH);
  digitalWrite(LEFT_B1, LOW);
  digitalWrite(RIGHT_A2, HIGH);
  digitalWrite(RIGHT_B2, LOW);
}

void forwardi (){
  digitalWrite(LEFT_A1, HIGH);
  digitalWrite(LEFT_B1, LOW);
  digitalWrite(RIGHT_A2, HIGH);
  digitalWrite(RIGHT_B2, LOW);
  delay (2000);
}

void backward(){
  digitalWrite(LEFT_A1, LOW);
  digitalWrite(LEFT_B1, HIGH);
  digitalWrite(RIGHT_A2, LOW);
  digitalWrite(RIGHT_B2, HIGH);
  delay(1000);
}

void left(){
  digitalWrite(LEFT_A1, LOW);
  digitalWrite(LEFT_B1, HIGH);
  digitalWrite(RIGHT_A2, HIGH);
  digitalWrite(RIGHT_B2, LOW);
  delay(500);
}

void right(){
  digitalWrite(LEFT_A1, HIGH);
  digitalWrite(LEFT_B1, LOW);
  digitalWrite(RIGHT_A2, LOW);
  digitalWrite(RIGHT_B2, HIGH);
  delay(500);
}

void stop(){
  digitalWrite(LEFT_A1, LOW);
  digitalWrite(LEFT_B1, LOW);
  digitalWrite(RIGHT_A2, LOW);
  digitalWrite(RIGHT_B2, LOW);
  delay(3000);
}

These functions define how to control the robot’s motors to perform different movements:

  • forward(): Sets the motor control pins to make the robot move forward. Typically, for DC motors and common motor drivers, setting one pin HIGH and the other LOW on each motor will result in forward motion.
  • forwardi(): Similar to forward(), but includes a delay(2000); of 2 seconds. This makes the robot move forward for a specific duration. The ‘i’ likely stands for “intermediate” or “interval”.
  • backward(): Sets the motor control pins to move the robot backward. This usually involves reversing the logic of the motor control pins compared to the forward() function. It also includes a delay(1000); of 1 second, making it move backward for a specific duration.
  • left(): Turns the robot left. This is often achieved by stopping or slowing down the left motor while keeping the right motor moving forward (or moving backward the left motor and forward the right motor, depending on the robot’s design and motor driver). It includes a delay(500); for a timed turn.
  • right(): Turns the robot right, similarly achieved by controlling the motors differentially. It also includes a delay(500); for a timed turn.
  • stop(): Stops both motors by setting all motor control pins LOW. It includes a delay(3000); of 3 seconds, making the robot stop for a specific duration.

Taking Your Arduino Robot Car Programming Further

This code provides a fundamental framework for arduino robot car programming focused on obstacle avoidance. To enhance your robot car and delve deeper into robotics, consider these expansions:

  • Refine Obstacle Avoidance Logic: The current avoidance maneuver is fixed. You could make it more intelligent by:
    • Using sensor readings during the maneuver to adjust the turns and movements dynamically.
    • Implementing different avoidance strategies based on the situation (e.g., turning more sharply if the obstacle is very close).
    • Using multiple sensors (e.g., adding ultrasonic sensors for wider detection range or side IR sensors for better cornering).
  • Add Speed Control: Instead of just HIGH and LOW for motor control, use PWM (Pulse Width Modulation) to control motor speed, allowing for smoother movements and more nuanced control.
  • Remote Control: Integrate Bluetooth or Wi-Fi modules to control your robot car remotely using a smartphone app or a web interface.
  • Line Following: Add line sensors and program your robot to follow a black line on a white surface, or vice versa.
  • Autonomous Navigation: Explore more advanced navigation algorithms like path planning and SLAM (Simultaneous Localization and Mapping) for truly autonomous robots.

Conclusion

This exploration into arduino robot car programming with obstacle avoidance is just the beginning. By understanding the basic code structure, experimenting with modifications, and adding more features, you can build increasingly sophisticated and capable robots. The Arduino platform, combined with your creativity, opens up a vast world of possibilities in robotics and automation. Start coding, start building, and enjoy the journey of bringing your robotic creations to life!

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *