How to Make an Obstacle Avoiding Robot | Arduino

In this post, I’ll show you how to give your robot the ability to “see.” We’ll create an obstacle avoiding robot using Arduino and an ultrasonic sensor.

Shout out to the late Gordon McComb for this project idea. He is the author of an excellent book that I recommend buying if you’re getting started with robotics: How to Make a Robot.

An ultrasonic sensor works by producing high frequency sound waves and then measuring the time it takes for the sound to reflect back to the sensor. Objects that are closer to the robot reflect sound back faster than objects that are farther away. This data is then used by the robot to avoid running into objects. Bats use ultrasound in order to locate food and avoid obstacles inside dark caves. Dolphins emit ultrasound as well in order to detect and recognize objects.

dolphin_ocean_waves_jump

Video

Here is a video of what we will build in this tutorial.

Requirements

Here are the requirements:

  • Make a robot that avoids obstacles using an ultrasonic sensor.

You Will Need

The following components are used in this project. You will need:

Directions

First, get your ultrasonic distance sensor and place the far left pin (the one labeled VCC, the supply voltage) into the solderless breadboard in cell j12.

Now, wire the ultrasonic sensor to the Arduino as follows. Remember that each cell in a single row of 5 cells on a solderless breadboard is electrically connected (e.g. j12 is connected to f12, g12, h12, and i12 electrically):

  • VCC on the sensor connects to 5V on the Arduino
  • Echo on the sensor connects to Digital Pin 8 on the Arduino
  • Trig (stands for trigger) on the sensor connects to Digital Pin 7 on the Arduino
  • GND (stands for Ground) on the sensor connects to ground on the solderless breadboard
obstacle-avoiding-robot-1
obstacle-avoiding-robot-2

Now, upload the following sketch to the Arduino to test the ultrasonic sensor.

/**
 *  This program tests the ultrasonic
 *  distance sensor
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-13
 */

/* Give a name to a constant value before
 * the program is compiled. The compiler will 
 * replace references to Trigger and Echo with 
 * 7 and 8, respectively, at compile time.
 * These defined constants don't take up 
 * memory space on the Arduino.
 */
#define Trigger 7
#define Echo 8

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup(){

  // Set the baud rate to 9600. 9600 means that 
  // the serial port is capable of transferring 
  // a maximum of 9600 bits per second.
  Serial.begin(9600);

  // Define each pin as an input or output.
  pinMode(Echo, INPUT);
  pinMode(Trigger, OUTPUT);
}

void loop(){

  // Make the Trigger LOW (0 volts) 
  // for 2 microseconds
  digitalWrite(Trigger, LOW);
  delayMicroseconds(2);

  // Emit high frequency 40kHz sound pulse
  // (i.e. pull the Trigger) 
  // by making Trigger HIGH (5 volts) 
  // for 10 microseconds
  digitalWrite(Trigger, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trigger, LOW); 

  // Detect a pulse on the Echo pin 8. 
  // pulseIn() measures the time in 
  // microseconds until the sound pulse
  // returns back to the sensor.
  int distance = pulseIn(Echo, HIGH);

  // Speed of sound is:
  // 13511.811023622 inches per second
  // 13511.811023622/10^6 inches per microsecond
  // 0.013511811 inches per microsecond
  // Taking the reciprocal, we have:
  // 74.00932414 microseconds per inch 
  // Below, we convert microseconds to inches by 
  // dividing by 74 and then dividing by 2
  // to account for the roundtrip time.
  distance = distance / 74 / 2;

  // Print the distance in inches
  Serial.println(distance);

  // Pause for 100 milliseconds
  delay(100);
}

As soon as uploading is finished and with the USB cable still connected to the Arduino, click on the green magnifying glass in the upper right of the IDE to open the Serial Monitor.

Make sure you have the following settings:

  • Autoscroll: selected
  • Line ending: No Line ending
  • Baud: 9600 baud

Place any object in front of the sensor and move it back and forth. You should see the readings on the Serial Monitor change accordingly.

Now, close the Serial Monitor and upload the following sketch to the Arduino.

#include <Servo.h> 

/**
 * This robot avoids obstacles 
 * using an ultrasonic sensor.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-13
 */

// Create two servo objects, one for each wheel
Servo right_servo;
Servo left_servo;

/* Give a name to a constant value before
 * the program is compiled. The compiler will 
 * replace references to Trigger and Echo with 
 * 7 and 8, respectively, at compile time.
 * These defined constants don't take up 
 * memory space on the Arduino.
 */
#define Trigger 7
#define Echo 8

/*   
 *  This setup code is run only once, when 
 *  Arudino is supplied with power.
 */
void setup(){
  
  // Set the baud rate to 9600. 9600 means that 
  // the serial port is capable of transferring 
  // a maximum of 9600 bits per second.
  Serial.begin(9600);

  right_servo.attach(9);      // Right servo to pin 9
  left_servo.attach(10);      // Left servo to pin 10  

  // Define each pin as an input or output.
  pinMode(Echo, INPUT);
  pinMode(Trigger, OUTPUT);

  // Initializes the pseudo-random number generator
  // Needed for the robot to wander around the room
  randomSeed(analogRead(3));

  delay(200);     // Pause 200 milliseconds               
  go_forward();   // Go forward
}

/*
 * This is the main code that runs again and again while
 * the Arduino is connected to power.
 */
void loop(){
  int distance = doPing();

  // If obstacle <= 2 inches away
  if (distance >= 0 && distance <= 2) {    
    Serial.println("Obstacle detected ahead");  
    go_backwards();   // Move in reverse for 0.5 seconds
    delay(500);

    /* Go left or right to avoid the obstacle*/
    if (random(2) == 0) {  // Generates 0 or 1, randomly        
      go_right();  // Turn right for one second
    }
    else {
      go_left();  // Turn left for one second
    }
    delay(1000);
    go_forward();  // Move forward
  }
  delay(50); // Wait 50 milliseconds before pinging again
}

/*
 * Returns the distance to the obstacle as an integer
 */
int doPing () {
  int distance = 0;
  int average = 0;

  // Grab four measurements of distance and calculate
  // the average.
  for (int i = 0; i < 4; i++) {

    // Make the Trigger LOW (0 volts) 
    // for 2 microseconds
    digitalWrite(Trigger, LOW);
    delayMicroseconds(2);

    
    // Emit high frequency 40kHz sound pulse
    // (i.e. pull the Trigger) 
    // by making Trigger HIGH (5 volts) 
    // for 10 microseconds
    digitalWrite(Trigger, HIGH);
    delayMicroseconds(10);
    digitalWrite(Trigger, LOW);
     
    // Detect a pulse on the Echo pin 8. 
    // pulseIn() measures the time in 
    // microseconds until the sound pulse
    // returns back to the sensor.    
    distance = pulseIn(Echo, HIGH);

    // Speed of sound is:
    // 13511.811023622 inches per second
    // 13511.811023622/10^6 inches per microsecond
    // 0.013511811 inches per microsecond
    // Taking the reciprocal, we have:
    // 74.00932414 microseconds per inch 
    // Below, we convert microseconds to inches by 
    // dividing by 74 and then dividing by 2
    // to account for the roundtrip time.
    distance = distance / 74 / 2;

    // Compute running sum
    average += distance;

    // Wait 10 milliseconds between pings
    delay(10);
  }

  // Return the average of the four distance 
  // measurements
  return (average / 4);
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  right_servo.write(180);
  left_servo.write(0);
}
void go_right() {
  right_servo.write(180);
  left_servo.write(180);
}
void go_left() {
  right_servo.write(0);
  left_servo.write(0);
}
void stop_all() {
  right_servo.write(90);
  left_servo.write(90);
}

Disconnect the USB cable from the Arduino, and place the Arduino on the floor.

Turn on the servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON

Then plug in the Arduino’s power.

Watch the Obstacle Avoiding Robot move!

obstacle-avoiding-robot-3

How to Make an Object Detection Robot | Arduino

In this post, I’ll show you how to make an object detection robot using Arduino. This robot will move around a room and when it bumps into an object, it will turn around and go in another direction. Reminds me of the iRobot vacuum cleaner!

Shout out to the late Gordon McComb for this project idea. He is the author of an excellent book that I recommend buying if you’re getting started with robotics: How to Make a Robot.

roomba_discovery

Requirements

Here are the requirements:

  • Make a robot that can turn around and go in a different direction after bumping into an object.

You Will Need

The following components are used in this project. You will need:

Directions

First, I position the snap action switches so that the corners are aligned with the side and front of the lower base of the robot. I will make a mark with a pencil to indicate where I should glue (we’ll glue them down later).

object_detection_robot-2
object_detection_robot-1

Grab three pieces of 6-inch male-to-female jumper wire.

object_detection_robot-3

Cut off the female end of the jumper wire.

object_detection_robot-4

Remove 0.25 inches of insulation from the end of the wire that you just cut.

Twist the loose ends of each wire.

object_detection_robot-5
object_detection_robot-6

Before you solder, it is helpful to first stick the wire strands through the pinhole of the terminal.

object_detection_robot-8
object_detection_robot-9

Solder one wire to the NO metal terminal of a switch (black wire).

Solder one wire to the NO metal terminal of the other switch (brown wire).

Solder one wire to the COM terminal of the switch that will go on the right side of the robot (white wire).

Get 3 inches of solder wire and connect the COM terminals of both switches (yellow wire).

object_detection_robot-7
object_detection_robot-11
object_detection_robot-12
object_detection_robot-10

If you don’t know how to solder, check out this video (skip to the soldering part):

Now we need to test the switches.

Plug the jumper connected to the Right switch COM into Digital Pin 4 on the Arduino.

Plug the jumper connected to the Right switch NO into Digital Pin 2 on the Arduino.

Plug the jumper connected to the Left switch NO into Digital Pin 3 on the Arduino.

object_detection_robot-13

Now, upload the following code to the Arduino. When you press down one of the switches, the built-in LED on the Arduino should light up.

/**
 * This program is to test the snap action switches
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-12
 */

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() {

  // Pin 13 is LED output
  pinMode(LED_BUILTIN, OUTPUT);
  
  pinMode(2, INPUT);  // Right Switch
  pinMode(3, INPUT);  // Left Switch
  pinMode(4, OUTPUT); // Ground for Switches
  
  digitalWrite(2, HIGH); // Enable pullup resistors
  digitalWrite(3, HIGH); // Enable pullup resistors
  digitalWrite(4, LOW);  // Set ground to 0 volts
}


/*   
 * Light LED pin13 if pin 2 or 3 goes LOW (i.e. pressed)
 */
void loop() {
  if ((digitalRead(2) == LOW) || (digitalRead(3) == LOW))
    digitalWrite(LED_BUILTIN, HIGH);
  else
    digitalWrite(LED_BUILTIN, LOW);
  delay (100); 
}

If everything is working OK, go ahead and glue the switches to the lower base of the board.

object_detection_robot-14
object_detection_robot-15

Now, upload the following sketch to the Arduino, and then place the Arduino on the floor.

#include <Servo.h> 

/**
 *  This robot will move around a room and when it 
 *  bumps into an object, it will turn around and 
 *  go in another direction.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-12
 */

// Create two servo objects, one for each wheel
Servo right_servo;
Servo left_servo;

// Volatile keyword is used because these variables
// can change at any time without any action having been
// taken by the compiled code. 

volatile int left_switch = LOW;   // Left switch flag
volatile int right_switch = LOW;  // Right switch flag
boolean already_started = false;  

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() {
  // Set the pin modes for the switches
  pinMode(2, INPUT); // Right switch is input
  pinMode(3, INPUT); // Left switch is input
  pinMode(4, OUTPUT); // Pin 4 is ground
  
  // Turn on the internal pull up resistors for the switches
  // Keeps input from floating when the switches are not
  // pressed
  digitalWrite(2, HIGH);   // Right switch default to high
  digitalWrite(3, HIGH);   // Left switch default to high
  digitalWrite(4, LOW);    // Pin 4 default is ground

  right_servo.attach(9);    // Right servo is pin 9
  left_servo.attach(10);    // Left servo is pin 10
 
  // Declare the interrupts
  // attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)
  // Interrupt when go from high to low
attachInterrupt(digitalPinToInterrupt(2), hit_right, FALLING); 
attachInterrupt(digitalPinToInterrupt(3), hit_left, FALLING);  
  
  already_started = true;  // Bot can now move
}

void loop() {
  if (left_switch == HIGH) {   // If the left switch is hit
    go_backwards();            // Go backwards for 1 sec
    delay(1000); 
    go_right();             // Turn to the right for 1 sec
    delay(1000);
    go_forward();              // Move forward
    left_switch = LOW;         // Reset the flag
  }
  
  if (right_switch == HIGH) {  // If the right switch is hit
    go_backwards();           // Go backwards for one second
    delay(1000); 
    go_left();                // Turn left for one second
    delay(1000);
    go_forward();             // Move forward
    right_switch = LOW;       // Reset the flag
  }
}
  
// Interrupt routine for left switch bumping into an object
void hit_left() {
  if (already_started)     // Valid if the program has begun
    left_switch = HIGH;    // Set flag high to get serviced
}

// Interrupt routine for right switch bumping into an object
void hit_right() {
  if (already_started)    // Valid if the program has begun
    right_switch = HIGH;  // Set flag high to get serviced
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  right_servo.write(180);
  left_servo.write(0);
}
void go_right() {
  right_servo.write(180);
  left_servo.write(180);
}
void go_left() {
  right_servo.write(0);
  left_servo.write(0);
}
/*
void stop_all() {
  right_servo.write(90); // Tweak the 90
  left_servo.write(90);  // Tweak the 90
}
*/

Power it up by turning on the servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON

Then plug in the Arduino’s power.

In order to actually start the program, you need to depress one of the switches. Make sure the Arduino is on the floor before you start the program.

Watch the Object Detection Robot move!

Video

How to Make an Autonomous Wheeled Robot Move | Arduino

In this post, I’ll show you how to make a basic autonomous wheeled robot move forwards, backwards, to the right, and to the left using Arduino.

Shout out to the late Gordon McComb for this project idea. He is the author of an excellent book that I recommend buying if you’re getting started with robotics: How to Make a Robot.

Requirements

Here are the requirements:

  • Make an autonomous wheeled robot move forwards, backwards, to the right, and to the left using Arduino.

You Will Need

The following components are used in this project. You will need:

Directions

First, we need to test the servos to see if they are working. Code up the sketch below into the Arduino Integrated Development Environment (IDE).

Give it a descriptive name like test_servos.ino.

1_code_the_sketchPNG
// Include library that enables us to work with servos
#include <Servo.h> 

/**
 * This program is a test of the servo motors 
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-11
 */

// Create two servo objects, one for each wheel
Servo right_servo;
Servo left_servo;

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() { 
  
  // Right servo is connected to digital pin 9
  right_servo.attach(9);   

  // Right servo is connected to digital pin 9
  left_servo.attach(10);
} 

/*   
 *  This code repeats as long as the Arduino has power.
 */
void loop() { 
  
  // On the continuous rotation servo, the write() 
  // method sets the speed of the servo.
  // 0 is full speed in one direction.
  // 180 is full speed in the other direction.
  // ~90 is no movement (You will have to tweak to
  //   get no movement).
  
  // Move forwards
  right_servo.write(0);  
  left_servo.write(180);

  // Wait 2 seconds
  delay(2000);

  // Move backwards (reverse)
  right_servo.write(180);  
  left_servo.write(0);

  // Wait 2 seconds
  delay(2000);
/*
  // Turn right
  right_servo.write(180); 
  left_servo.write(180);
  
  // Wait 2 seconds
  delay(2000);

  // Turn left
  right_servo.write(0);    
  left_servo.write(0);     
  
  // Wait 2 seconds
  delay(2000);
  */
}

Make sure the right and left servos are OFF:

  • a13 to j2 = left servo OFF
  • e13 to j28 = right servo OFF
2_servos_are_off

Compile the sketch in the IDE by clicking the checkmark in the upper left corner of the IDE.

3_compile_the_sketchPNG

Upload the sketch to the Arduino board by connecting the USB to your computer. Then click the right arrow (Upload) button on the IDE. The LED on your Arduino should be illuminated.

4_connect_usb
5_right_arrow_arduino_uploadPNG

Remove the USB cord from the Arduino.

Turn ON both servos:

  • a13 to e3 = left servo ON
  • e13 to e28 = right servo ON
6_servos_are_on

Hold the robot in your hand or place the robot on the floor.

Power up the Arduino by plugging in the 9V jack.

Observe the robot move.

7_moving_robot
8_moving_robot

When you are done watching it move, pull the 9V jack out of the Arduino and turn the servos OFF. Remember:

  • a13 to j2 = left servo OFF
  • e13 to j28 = right servo OFF

Here is another sketch (named basic_wheeled_bot.ino) that you can upload to the Arduino that adds some different movements to your robot and breaks up the movements we had in the test code into separate methods. Feel free to play around with this and create your own movement sequence:

// Include library that enables us to work with servos
#include <Servo.h> 

/**
 * This program makes a basic wheeled robot
 * do different movements.
 * 
 * @author Addison Sears-Collins
 * @version 1.0 2019-05-11
 */

// Create two servo objects, one for each wheel
Servo right_servo;
Servo left_servo;

/*   
 *  This setup code is run only once, when Arudino is 
 *  supplied with power.
 */
void setup() { 
  
  // Right servo is connected to digital pin 9
  right_servo.attach(9);   

  // Right servo is connected to digital pin 9
  left_servo.attach(10);
} 

/*   
 *  This code repeats as long as the Arduino has power.
 */
void loop() { 

  // On the continuous rotation servo, the write() 
  // method sets the speed of the servo.
  // 0 is full speed in one direction.
  // 180 is full speed in the other direction.
  // ~90 is no movement (You will have to tweak to
  //   get no movement).
  
  go_forward();

  // Pause 2 seconds
  delay(2000);

  go_backwards();

  // Pause 2 seconds
  delay(2000);
  
  go_right();

  // Pause 2 seconds
  delay(2000);
  
  go_left();

  // Pause 2 seconds
  delay(2000);
  
  stop_all();

  // Pause 2 seconds
  delay (2000);
}

/*   
 *  Forwards, backwards, right, left, stop.
 */
void go_forward() {
  right_servo.write(0);
  left_servo.write(180);
}
void go_backwards() {
  right_servo.write(180);
  left_servo.write(0);
}
void go_right() {
  right_servo.write(180);
  left_servo.write(180);
}
void go_left() {
  right_servo.write(0);
  left_servo.write(0);
}
void stop_all() {
  right_servo.write(90); // Tweak the 90
  left_servo.write(90);  // Tweak the 90
}

Video