Arduino Uno Car Program: Your Guide to Basic Robotics Code

Embarking on your Arduino robotics journey? Creating a car that can autonomously navigate is a fantastic starting point. This guide breaks down a fundamental “Arduino Uno Car Program” designed for beginners. We’ll explore the code, understand its logic, and lay the groundwork for more complex projects.

This program is crafted for an Arduino Uno, a popular microcontroller board, and focuses on basic car movement and obstacle avoidance using an ultrasonic sensor. Let’s dive into the code structure and functionality.

Code Breakdown: Understanding the Arduino Car Program

The code is written in C++ and designed for the Arduino environment. It’s structured into two main sections: setup() and loop(), along with several functions to control the car’s movement.

setup() Function: Initializing Your Arduino Car

The setup() function runs once at the beginning of your program. It’s used to initialize variables, pin modes, and start serial communication.

#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>: While included, this line isn’t actually used in this specific code. It’s likely a remnant from a project that might have used software serial communication. For this program, it’s unnecessary.
  • #define ...: These lines define constants, making the code more readable. LEFT_A1, LEFT_B1, RIGHT_A2, RIGHT_B2 are likely connected to motor driver pins controlling the left and right wheels. IR_TRIG and IR_ECHO are for the ultrasonic sensor’s trigger and echo pins. It’s worth noting that “IR_TRIG” and “IR_ECHO” are used in the code, while the comment mentions “IR sensor”. In fact, based on the code’s logic using pulseIn, it is indeed an ultrasonic sensor, not an Infrared (IR) sensor.
  • Serial.begin(9600): Initializes serial communication at 9600 bits per second, allowing you to send data from your Arduino to your computer for debugging and monitoring.
  • pinMode(..., OUTPUT) and pinMode(..., INPUT): These lines set the digital pins as either outputs (to control motors and trigger the sensor) or inputs (to read data from the sensor).

loop() Function: The Heart of Your Arduino Car Program

The loop() function runs continuously after setup() completes. This is where the main logic of your car program resides.

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();
  }
}

This section is responsible for:

  1. Distance Measurement:

    • digitalWrite(IR_TRIG, HIGH); delay(10); digitalWrite(IR_TRIG, LOW);: This sequence triggers the ultrasonic sensor to send out a sound wave. A short 10-millisecond pulse to the trigger pin is common for many ultrasonic sensors like the HC-SR04.
    • duration = pulseIn(IR_ECHO, HIGH);: This line measures the duration of the pulse received back by the echo pin. The pulseIn() function waits for the echo pin to go HIGH, starts timing, waits for it to go LOW, and returns the duration of the HIGH pulse in microseconds.
    • distance = ((float)(340 * duration) / 10000) / 2;: This calculates the distance to the object in centimeters. The speed of sound is approximately 340 meters per second (or 34000 cm/s). The formula converts the duration (in microseconds) to distance. The division by 2 is because the sound wave travels to the object and back.
  2. Obstacle Avoidance Logic:

    • while(distance < 20): This while loop is the core of the obstacle avoidance. As long as the measured distance is less than 20 cm, the car will execute the code within this loop.
    • stop();: The car stops when an obstacle is detected within 20cm.
    • sum++ ;: A counter sum is incremented in each loop iteration when an obstacle is detected.
    • The nested if(sum > 9) block initiates a sequence of movements if the obstacle is detected for more than 9 iterations. This sequence attempts to navigate around the obstacle: backward, left, forward (briefly – forwardi), right, forward (briefly twice), right again, forward (briefly), left, and finally forward. This is a pre-programmed obstacle avoidance routine.
    • The code includes redundant distance measurements and forward commands within the while loop and after it. These could be simplified for cleaner code.
  3. Movement Control based on Distance:

    • if(distance >= 20){ forward(); }: If the distance is 20cm or greater, the car moves forward. This is also present outside the while loop, ensuring forward movement when no obstacle is detected.

Movement Functions: Defining Car Actions

The code defines several functions to control the car’s movement: forward(), backward(), left(), right(), stop(), and forwardi().

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, LOW);
  delay(500);
}

void stop(){
  digitalWrite(LEFT_A1, LOW);
  digitalWrite(LEFT_B1, LOW);
  digitalWrite(RIGHT_A2, LOW);
  digitalWrite(RIGHT_B2, LOW);
  delay(3000);
}
  • Motor Control: Each function controls the direction of current flow to the motors connected to pins LEFT_A1, LEFT_B1, RIGHT_A2, and RIGHT_B2. By setting these pins HIGH or LOW in specific combinations, the motors rotate in different directions, achieving forward, backward, left, and right movements. The exact wiring and motor driver setup are crucial for these functions to work correctly with your car.
  • delay() in Movement Functions: Functions like backward(), left(), right(), stop(), and forwardi() include delay() functions. These introduce pauses in the car’s movement. For example, backward() delays for 1 second, left() and right() for 0.5 seconds, stop() for 3 seconds, and forwardi() for 2 seconds. forward() function does not have delay, meaning it should move forward continuously as long as it is called within the loop. forwardi() seems to be intended for a forward movement with a delay duration, potentially shorter “forward interval” than continuous forward.

Improving the Arduino Uno Car Program

This “arduino uno car program” provides a basic foundation. Here are some ways to enhance it:

  • Smoother Obstacle Avoidance: The current obstacle avoidance is quite rigid. Implementing a more sophisticated algorithm, perhaps involving turning angles proportional to the distance reading, would result in smoother navigation.
  • PID Control for Motors: For more precise motor control, especially for turning and straight-line movement, consider implementing PID (Proportional-Integral-Derivative) control.
  • Sensor Fusion: Adding more sensors, such as line followers or infrared sensors, could enable more complex behaviors and navigation strategies.
  • Code Optimization: The code has some redundancies (repeated distance measurements). Cleaning up the code and optimizing for efficiency is always a good practice.
  • Modular Design: Breaking down the code into more functions and classes would improve readability and maintainability, especially as the project grows more complex.

Conclusion: Your First Step in Arduino Car Programming

This “arduino uno car program” serves as an excellent starting point for anyone venturing into Arduino robotics and car projects. By understanding the code structure, the function of each part, and potential improvements, you’re well-equipped to modify and expand upon this program to create your own unique and intelligent robotic car. Experiment, learn, and enjoy the journey of robotics creation!

Alt text: A DIY Arduino Uno car robot with a mounted ultrasonic sensor and visible motor connections, showcasing a typical beginner robotics project setup.

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 *