Embarking on the journey of robotics is incredibly exciting, and coding is the heart that brings these machines to life. If you’re fascinated by robotics and looking to build your own autonomous vehicle, understanding how to code a robotics car is your first step. This guide will walk you through the fundamental code for creating a simple robotics car that can navigate its environment and avoid obstacles using an Arduino microcontroller.
Understanding the Code: Building an Obstacle-Avoiding Robot
The following code provides a basic framework for an obstacle-avoiding robotics car. We’ll break down each section to understand how it works:
#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);
}
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 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);
}
Code Breakdown: Step-by-Step
-
Include Library and Define Pins:
#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
#include <SoftwareSerial.h>
: This line includes the SoftwareSerial library, although it’s not actually used in this specific code. It’s often included as a standard practice in Arduino projects for potential serial communication needs.#define ...
: These lines define constants that assign names to the Arduino pins connected to the motors and the IR sensor. This makes the code more readable and easier to modify if you change pin assignments.LEFT_A1
,LEFT_B1
,RIGHT_A2
,RIGHT_B2
: These are likely connected to the motor driver for controlling the left and right motors of the car.IR_TRIG
,IR_ECHO
: These are for the ultrasonic distance sensor (often mistakenly referred to as IR in basic setups), whereTRIG
pin sends a trigger signal andECHO
pin receives the echo to calculate distance.
-
setup()
Function: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); }
Serial.begin(9600);
: Initializes serial communication at 9600 bits per second. This is used to send data from the Arduino to the serial monitor on your computer, helpful for debugging and monitoring sensor readings.pinMode(..., OUTPUT);
: Sets the specified pins as outputs. The motor control pins (LEFT_A1
,LEFT_B1
,RIGHT_A2
,RIGHT_B2
) and the IR sensor trigger pin (IR_TRIG
) need to send signals, so they are set asOUTPUT
.pinMode(IR_ECHO, INPUT);
: Sets the IR sensor echo pin (IR_ECHO
) as an input, as it receives signals back to the Arduino.
-
loop()
Function – The Main Control Logic: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); // ... (rest of the obstacle avoidance logic) ... } if(distance >= 20){ Serial.println("forward"); forward(); } }
-
Distance Measurement:
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);
This section measures the distance to an obstacle using an ultrasonic sensor:
digitalWrite(IR_TRIG, HIGH); delay(10); digitalWrite(IR_TRIG, LOW);
: Sends a short pulse to trigger the ultrasonic sensor.duration = pulseIn(IR_ECHO, HIGH);
: Measures the duration of the pulse received back by the echo pin. This duration is proportional to the distance.distance = ((float)(340 * duration) / 10000) / 2;
: Calculates the distance in centimeters. The speed of sound in air (approximately 340 m/s or 34000 cm/s) is used in the formula. The division by 10000 and 2 is for unit conversion (microseconds to seconds and one-way distance).Serial.print("nDistance : "); Serial.println(distance);
: Prints the measured distance to the serial monitor.
-
Obstacle Avoidance Logic (
while(distance < 20)
loop):int sum = 0; while(distance < 20) { Serial.println("stop"); stop(); sum++ ; Serial.println(sum); // ... (distance re-measurement and movement logic) ... if(sum > 9) { // ... (complex movement sequence) ... } }
int sum = 0;
: Initializes a counter variablesum
.while(distance < 20)
: This loop executes as long as the measured distance is less than 20 cm (indicating an obstacle is close).Serial.println("stop"); stop();
: Immediately stops the car when an obstacle is detected within 20cm. Thestop()
function (defined later) is called to halt the motors.sum++ ; Serial.println(sum);
: Increments thesum
counter and prints its value to the serial monitor. This counter seems to be used to trigger a more complex obstacle avoidance maneuver after the car has encountered an obstacle multiple times in a row.- Re-measuring Distance Inside the Loop: The code re-measures the distance again inside the
while
loop. This is important to continuously check if the obstacle is still present. - Movement Logic based on
sum
: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 the
sum
counter exceeds 9 (meaning the car has encountered obstacles multiple times consecutively), this block of code executes a sequence of movements to try and navigate around the obstacle:backward()
: Moves the car backward.left()
: Turns the car left.forwardi()
: Moves forward for a longer duration (2 seconds, as defined in theforwardi()
function).right()
: Turns the car right.- This sequence suggests an attempt to back away, turn left, move forward, turn right, and then move forward again, possibly to go around an obstacle that is directly in front.
sum = 0;
: Resets thesum
counter after executing the obstacle avoidance maneuver.
-
Forward Movement (outside the
while
loop):if(distance >= 20){ Serial.println("forward"); forward(); }
If the measured distance is 20cm or greater (no obstacle detected), the car moves forward by calling the
forward()
function.
-
-
Movement Functions (
forward()
,backward()
,left()
,right()
,stop()
,forwardi()
):
These functions control the motors to make the car move in different directions:forward()
: Moves the car forward by setting the motor control pins (LEFT_A1
,RIGHT_A2
) HIGH and (LEFT_B1
,RIGHT_B2
) LOW.forwardi()
(Forward with delay): Moves forward for 2 seconds (delay(2000);
).backward()
: Moves backward for 1 second (delay(1000);
).left()
: Turns left for 0.5 seconds (delay(500);
). It achieves this by making the left side motors move backward and the right side motors move forward.right()
: Turns right for 0.5 seconds (delay(500);
). It achieves this by making the right side motors move backward and the left side motors move forward.stop()
: Stops the car by setting all motor control pins LOW and waits for 3 seconds (delay(3000);
).
A robotics car utilizing Arduino for its control system, demonstrating the application of coding in autonomous vehicle technology.
Enhancements and Further Learning
This code provides a basic foundation for Coding A Robotics Car. To make your robot more sophisticated, consider these improvements:
- Improved Obstacle Avoidance: The current obstacle avoidance is quite basic. You could enhance it by:
- Adding more sensors: Use multiple ultrasonic sensors (front, left, right) or infrared sensors for wider obstacle detection and better spatial awareness.
- More intelligent navigation: Implement more complex algorithms to navigate around obstacles more effectively, perhaps even mapping the environment.
- PID Control for Motors: For smoother and more precise movements, especially in turns and straight lines, explore PID (Proportional-Integral-Derivative) control for motor speed regulation.
- Remote Control: Add Bluetooth or Wi-Fi modules to control your car remotely using a smartphone or computer.
- Line Following: Integrate line sensors to enable your robot to follow a designated path.
- Machine Learning: For advanced projects, consider incorporating machine learning for object recognition or more adaptive navigation.
Coding a robotics car is a fantastic way to learn about programming, electronics, and mechanics. This basic obstacle avoidance example is just the beginning. As you delve deeper, you can create increasingly complex and intelligent robotic systems. Happy coding!