Creating an Obstacle avoiding Robot with Arduino, Adafruit Motor Shield v1 and Ultra-sonic Sensor

Written by Prithwiraj Bose on . Posted in Hobby Centre, Programming Tips Tricks Tutorials

Let’s make an Obstacle avoiding Robot. In this brief tutorial I will show how to build a perfect obstacle avoiding (run-away) robot using Arduino. I have used an Ultrasonic sensor mounted on a Servo Motor and a motor Shield for this project. The motor driver is Adafruit Motor Shield. This single shield is capable of controlling upto 4 DC motos and 1 servo motor simultaneously. Download link for the Arduino Robot Project Code (Arduino Sketch along with the required libraries) is available below. In this tutorial, I have not highlighted the instructions to setup the Robotic chassis along with BO Motors, Caster Wheel, Arduino Board etc. Rather I have concentrated on the how to extend the circuits to make it usable, connect the circuits and write the Arduino Sketch to make the Motors rotate by sensing the distance from Obstacles. When I created my first Arduino based Obstacle avoiding Robot, I was pretty much done with the mechanical connection, before getting stuck into the circuitry and programming. These were the 2 areas, where I struggled a lot and had to refer multiple tutorials to get a complete road-map. Here I will try to address those problems, which are often encountered by Newbies.

 

Parts List To Create the Arduino based Obstacle avoiding Robot

  1. Arduino Uno R3 board (1 pc)
  2. Adafruit Motor Shield v1 for Arduino Uno (1 pc)
  3. HC-SR04 Ultra-sonic distance sensor for Arduino (1 pc)
  4. 6v – 12v DC general purpose servo motor with accessories (1 pc)
  5. 100-300 RPM 5v – 12v DC Motor L-Shape with Wheels and Clamps (2 pcs each)
  6. Caster Wheel (1 pc)
  7. Robotic Chassis (1 pc)
  8. 9v Rechargeable Ni-MH Battery 180 – 500 mAh, PP3 size (1 pc)
  9. Female to Female type Jumper wires (5 pcs)
  10. Connecting Wires insertable in Bread-board (50 cm)
  11. 12v three Pin on/off switch (1 pc)
  12. Battery connector (1 pc)
  13. Solderable Male Header Pins (4 pcs)
  14. Screws, Nut-Bolts, Black-tape
  15. Soldering Kit

 

Buy All of These Items – DIY KIT

 

I am using a 9v rechargeable Ni-MH battery. A use-and-throw battery will also work. But remember, you need many of them, because the Obstacle avoiding Robot will exhaust the charge in 10-15 mins while running. I am using 2 ready-to-use L-Shaped 100 RPM 6v-12v Motors (often called BO Motor or Battery Operated Motor), widely used in Robotics along with a pair of Robotic wheels. If you need any help to choose the right Parts while purchasing online, write down in the ‘Comments’ section below; I will respond. You might need to choose a right voltage regulated power supply if you use batteries of higher voltage.

 

Adafruit Motor Shield is really a wonderful board to build Arduino based Obstacle avoiding Robot. The important part is to identify the right version of the board. Most of the Adafruit Motor Shields, available in India today are version 1, so refer the documentation of Adafruit Motor Shield v1, not v2. In order to use Adafruit Motor Shield you have to download and install the Adafruit Motor Shield library v1. You can download it from here; installation is nothing but extracting the zipped folder inside your ARDUINO_INSTALLATION_FOLDER\lirary directory. So the path of the AFMotor.h file looks something like this: c:\Program Files (x86)\Arduino\library\Adafruit_Motor\AFMotor.h

In this tutorial, I have used an Arduino Uno R3 board. My perception is, most of you who are new to Arduino, use Uno for the first time. But you would face a problem after attaching the Adafruit Motor Shield on top of Arduino Uno. There won’t be any input, output or power pin left open for connecting other shields or modules to the Arduino. To address this problem you have to solder male (or female) header pins on the Adafruit Motor Shield board. Refer the diagram given below to solder the pins on Adafruit Motor Shield.

Solder Header Pins on Adafruit Motor Shield V1 To Attach Ultrasonic Sensor

Adafruit Motor Shield board already has marked slots to solder header pins. So, you don’t need to struggle to find a suitable place on the board. Atleast following pins must be soldered to attach the Ultrasonic sensor.

  • 2 pins in any 2 slots in the row marked as A0-5, (I used A4 and A5).
  • 1 pin in any of the slots in the row marked as 5v
  • 1 pin in the slot marked as Ground

In the diagram, you will see that I have soldered additional pins than what I’ve mentioned above. Those are for future use. Ah! Now you are ready to connect the sensors and power up the device. I am using a widely used Ultrasonic sensor for sensing obstacles. Ultrasonic sensors are cheap, readily available and easy to use. I am using a 4 pin Ultrasonic sensor with 1 Trigger pin, 1 Echo pin, 1 Vcc pin and 1 Ground pin. I will use Arduino’s NewPing library to use the sensor in Ping mode. You can download the NewPing library from here, as it doesn’t come pre-loaded with Arduino IDE as of today. Using Jumper wires connect Trigger pin of Ultra-sonic sensor to A4 pin, and Echo pin to A5 pin, Vcc pin of Ultra-sonic sensor to 5v pin and Ground pin to the Ground pin of the Adafruit Motor Shield. See the image below to complete this connection.

Connecting Ultrasonic Sensor on Adafruit Motor Shield v1

So, following pins should be connected:

  • USSensor.Trigger – AFShield.A4
  • USSensor.Echo – AFShield.A5
  • USSensor.Vcc – AFShield.5v
  • USSensor.Ground – AFShield.Ground

I am making a 2 wheel drive Obstacle avoiding Robot. I am assuming, you have already got the DC motors clamped on the Robotic chassis and the caster wheel affixed at the front of the chassis. Adafruit Motor Shield has total 4 slots for connecting DC motors. Since we have only 2 motors to control, we will use M1 and M4 position on the shield (you can use other 2 positions as well). There are 2 set of screw terminals on Adafruit Motor Shield. Each set contains total 5 points. Remember to use 2 of them from the edge, leaving the middle one unused. It is the ground point, and you won’t need that for DC motors. As far as the rotation direction of the motor is concerned, just connect the motor wires to the shield, complete the remaining steps, run the Arduino and see if the 2 wheels rotate in expected and same direction or not. If not, swap the wires of the motor, which rotates in wrong direction.

The Adafruit Motor Shield has dedicated slots for connecting 2 servo motors. I am using Servo2 slot to connect the Servo Motor. After connecting the servo motor, affix the Ultrasonic Sensor on top of the metallic (or plastic) shaft of the Servo Motor. If you don’t have a shaft with your Servo, you can use a piece of card-board and glue to paste it. Next part is to power-up the Adafruit Motor Shield. I am using a 9v rechargeable battery. Attaching the Ultra-sonic sensor on top of the Servo Motor could be confusing. You might have a question in mind that, which angle to fix the sensor at. Lets keep it simple. For first time, ensure that the sensor is facing forward toward the the Robot’s front-end, as if it sees straight towards its path. Once, the Arduino program is loaded and you start using the Obstacle avoiding Robot, you might need to attach and detach the sensor from the servo number of times. Roughly ensure that the maximum angle of rotation of the sensor from the central axis in each direction (left and right) is same when the Servo is operating. This is a fairly working approach to attach the sensor 2nd time onward. There is a pair of screw terminal designated to power up the board. I have used a 3 pin switch (on-off) between the positive end of the board and the battery. Refer the below diagram to connect the DC motors, Servo Motor and battery.

Connecting DC and Servo motors to Adafruit Motor Shield v1

Now that we are pretty much done with the Adafruit Motor Shield, we will concentrate on the Arduino part of it. Adafruit Motor Shield fits perfectly on Arduino Uno board. So, place the Adafruit Motor Shield on top of Uno and insert the male headers of the shield inside the female I/O and power pins of the Uno board. When done the 2 boards should become an attached single unit. As final step, connect the Arduino Uno with your computer using the USB cable, open Arduino IDE and create a new Sketch. Copy the following code inside the sketch, save, compile and upload it to the Uno and disconnect the USB cable.

 

#include <AFMotor.h>
#include <Servo.h>
#include <NewPing.h>
 
#define TRIG_PIN A4 // Pin A4 on the Motor Drive Shield connected to the ultrasonic sensor
#define ECHO_PIN A5 // Pin A5 on the Motor Drive Shield connected to the ultrasonic sensor
#define MAX_DISTANCE_POSSIBLE 1000 // sets maximum useable sensor measuring distance to 1000cm
#define MAX_SPEED 120 // sets speed of DC traction motors to 120/256 or about 47% of full speed - to reduce power draining.
#define MOTORS_CALIBRATION_OFFSET 3 // this sets offset to allow for differences between the two DC motors
#define COLL_DIST 20 // sets distance at which the Obstacle avoiding Robot stops and reverses to 10cm
#define TURN_DIST COLL_DIST+10 // sets distance at which the Obstacle avoiding Robot looks away from object (not reverse) to 20cm (10+10)
NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE_POSSIBLE); // sets up sensor library to use the correct pins to measure distance.
 
AF_DCMotor leftMotor(1, MOTOR12_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
AF_DCMotor rightMotor(4, MOTOR34_1KHZ); // create motor #2, using M2 output, set to 1kHz PWM frequency
Servo neckControllerServoMotor;  // create servo object to control a servo
 
int pos = 0; // this sets up variables for use in the sketch (code)
int maxDist = 0;
int maxAngle = 0;
int maxRight = 0;
int maxLeft = 0;
int maxFront = 0;
int course = 0;
int curDist = 0;
String motorSet = "";
int speedSet = 0;
 
//-------------------------------------------- SETUP LOOP ----------------------------------------------------------------------------
void setup() {
  neckControllerServoMotor.attach(9);  // attaches the servo on pin 9 (SERVO_2 on the Motor Drive Shield to the servo object
  neckControllerServoMotor.write(90); // tells the servo to position at 90-degrees ie. facing forward.
  delay(2000); // delay for two seconds
  checkRoute(); // run the CheckRoute routine to find the best Route to begin travel
  motorSet = "FORWARD"; // set the director indicator variable to FORWARD
  neckControllerServoMotor.write(90); // ensure servo is still facing forward
  moveForward(); // run function to make Obstacle avoiding Robot move forward
}
//------------------------------------------------------------------------------------------------------------------------------------
 
//---------------------------------------------MAIN LOOP ------------------------------------------------------------------------------
void loop() {
  checkForward(); // check that if the Obstacle avoiding Robot is supposed to be moving forward, that the drive motors are set to move forward - this is needed to overcome some issues with only using 4 AA NiMH batteries
  checkRoute(); // set ultrasonic sensor to scan for any possible obstacles
}
//-------------------------------------------------------------------------------------------------------------------------------------
void checkRoute() {
  int curLeft = 0;
  int curFront = 0;
  int curRight = 0;
  int curDist = 0;
  neckControllerServoMotor.write(144); // set servo to face left 54-degrees from forward
  delay(120); // wait 120milliseconds for servo to reach position
  for (pos = 144; pos > = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
  {
    neckControllerServoMotor.write(pos);  // tell servo to go to position in variable 'pos'
    delay(90); // wait 90ms for servo to get to position
    checkForward(); // check the Obstacle avoiding Robot is still moving forward
    curDist = readPing(); // get the current distance to any object in front of sensor
    if (curDist < COLL_DIST) { // if the current distance to object is less than the collision distance
      checkCourse(); // run the checkCourse function
      break; // jump out of this loop
    }
    if (curDist < TURN_DIST) { // if current distance is less than the turn distance
      changeRoute(); // run the changeRoute function
    }
    if (curDist > curDist) {
      maxAngle = pos;
    }
    if (pos > 90 && curDist > curLeft) {
      curLeft = curDist;
    }
    if (pos == 90 && curDist > curFront) {
      curFront = curDist;
    }
    if (pos < 90 && curDist > curRight) {
      curRight = curDist;
    }
  }
  maxLeft = curLeft;
  maxRight = curRight;
  maxFront = curFront;
}
//-------------------------------------------------------------------------------------------------------------------------------------
void setCourse() { // set direction for travel based on a very basic distance map, simply which direction has the greatest distance to and object - turning right or left?
  if (maxAngle < 90) {
    turnRight();
  }
  if (maxAngle > 90) {
    turnLeft();
  }
  maxLeft = 0;
  maxRight = 0;
  maxFront = 0;
}
//-------------------------------------------------------------------------------------------------------------------------------------
void checkCourse() { // we're about to hit something so move backwards, stop, find where the empty Route is.
  moveBackward();
  delay(500);
  moveStop();
  setCourse();
}
//-------------------------------------------------------------------------------------------------------------------------------------
void changeRoute() {
  if (pos < 90) {
    lookLeft(); // when current position of sensor is less than 90-degrees, it means the object is on the right hand side so look left
  }
  if (pos > 90) {
    lookRight(); // when current position of sensor is greater than 90-degrees, it means the object is on the left hand side so look right
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
 
int readPing() { // read the ultrasonic sensor distance
  delay(70);
  unsigned int uS = sonar.ping();
  int cm = uS / US_ROUNDTRIP_CM;
  return cm;
}
//-------------------------------------------------------------------------------------------------------------------------------------
void checkForward() {
  if (motorSet == "FORWARD") {
    leftMotor.run(FORWARD);  // ensure motors are going forward
    rightMotor.run(FORWARD);
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
void checkBackward() {
  if (motorSet == "BACKWARD") {
    leftMotor.run(BACKWARD);  // ensure motors are going backward
    rightMotor.run(BACKWARD);
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
 
// In some cases, the Motor Drive Shield may just stop if the supply voltage is too low (due to using only four NiMH AA cells).
// The above functions simply remind the Shield that if it's supposed to go forward, then ensure it is going forward and vice versa.
 
//-------------------------------------------------------------------------------------------------------------------------------------
void moveStop() {
  leftMotor.run(RELEASE);  // stop the motors.
  rightMotor.run(RELEASE);
}
//-------------------------------------------------------------------------------------------------------------------------------------
void moveForward() {
  motorSet = "FORWARD";
  leftMotor.run(FORWARD);      // turn it on going forward
  rightMotor.run(FORWARD);      // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
    rightMotor.setSpeed(speedSet);
    delay(5);
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
void moveBackward() {
  motorSet = "BACKWARD";
  leftMotor.run(BACKWARD);      // turn it on going forward
  rightMotor.run(BACKWARD);     // turn it on going forward
  for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
  {
    leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
    rightMotor.setSpeed(speedSet);
    delay(5);
  }
}
//-------------------------------------------------------------------------------------------------------------------------------------
void turnRight() {
  motorSet = "RIGHT";
  leftMotor.run(FORWARD);      // turn motor 1 forward
  rightMotor.run(BACKWARD);     // turn motor 2 backward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  leftMotor.run(FORWARD);      // set both motors back to forward
  rightMotor.run(FORWARD);
}
//-------------------------------------------------------------------------------------------------------------------------------------
void turnLeft() {
  motorSet = "LEFT";
  leftMotor.run(BACKWARD);     // turn motor 1 backward
  rightMotor.run(FORWARD);      // turn motor 2 forward
  delay(400); // run motors this way for 400ms
  motorSet = "FORWARD";
  leftMotor.run(FORWARD);      // turn it on going forward
  rightMotor.run(FORWARD);      // turn it on going forward
}
//-------------------------------------------------------------------------------------------------------------------------------------
void lookRight() {
  rightMotor.run(BACKWARD);  // looking right? set right motor backwards for 400ms
  delay(400);
  rightMotor.run(FORWARD);
}
//-------------------------------------------------------------------------------------------------------------------------------------
void lookLeft() {
  leftMotor.run(BACKWARD);  // looking left? set left motor backwards for 400ms
  delay(400);
  leftMotor.run(FORWARD);
}
//-------------------------------------------------------------------------------------------------------------------------------------

 

Since you have a 9v battery connected to the Adafruit Motor Shield, it will power up the Uno board underneath. Well, you are done to start the Obstacle avoiding Robot. Place it on a plain surface and turn on the switch to power up the robot. Let the robot run and avoid obstacles and see how it goes. You can play around with the code to change the behavior of the Obstacle avoiding Robot and the way it deals with obstacles.

 

 

Download the Arduino Sketch (.ino) and the required libraries (NewPing and Adafruit Motor Shield v1) here.

 

Buy This Robot’s DIY KIT

 

 

Photos & Videos

Although I am not a great fan of video or photo based tutorials, but Robotics is an area where seeing what are going to do helps you understand the tutorial better. I thought, I must show how my version of the Obstacle avoiding Robot looks like. See the video and the images of my Robot below, it works perfectly.

 

 

Compilation error issue resolved

Many readers were complaining about a compilation error. Yes, I noticed it. I had used wrong constant names at couple of places which resulted in following compilation error:

Arduino_Adafruit_RunAway_Robot:14: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
Arduino_Adafruit_RunAway_Robot:15: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
‘leftrightMotor_1KHZ’ was not declared in this scope

I have corrected the code and it works fine now. Many readers are actually complaining about various other errors which are not valid. In the attachment, I have provided couple of Arduino libraries which has to be installed in your IDE to compile the code successfully. Download the zip file, extract it and copy the 2 folders inside library folder to your installed Arduino IDE’s library folder [ Possibly here if on Windows: C:\Program Files (x86)\Arduino\libraries ]. And then re-start Arduino IDE and open the .ino file inside the zip with Arduino IDE, or copy paste the code in a new Sketch and try to compile and upload. It should work. If not, please let me know, I will be happy to help.

Tags: , , , , , , , , , , , , , , ,

Trackback from your site.

Prithwiraj Bose

I am an Architect of Distributed Applications of Information Services Industries in TATA Consultancy Services Ltd. I live in Kolkata, India. I love computers, programming, travelling and singing. Photography, spending time with my aquarium, designing a random website, painting, and singing are my favorite pass time. I've recently grown interest in Electronics, IoT and Robotics.

Comments (20)

  • Frank Nelvig

    |

    Hi!
    I keep getting this message (leftrightMotor_1KHZ’ was not declared in this scope) when compiling your script. I have followed your description and as you can see I’m using the right library even if I have more installed. Please help me- What do I do wrong?

    Arduino:1.8.1 (Mac OS X), TD: 1.35, Kort:”Arduino/Genuino Uno”

    Robot2:14: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
    AF_DCMotor leftMotor(1, leftrightMotor_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
    ^
    Robot2:15: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
    AF_DCMotor rightMotor(4, leftrightMotor_1KHZ); // create motor #2, using M2 output, set to 1kHz PWM frequency
    ^
    /Users/franknelvig/Documents/Arduino/Robot2/Robot2.ino: In function ‘void checkRoute()’:
    Robot2:54: error: ‘gt’ was not declared in this scope
    for (pos = 144; pos & gt; = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
    ^
    Robot2:54: error: expected primary-expression before ‘=’ token
    for (pos = 144; pos & gt; = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
    ^
    Robot2:54: error: expected ‘)’ before ‘;’ token
    for (pos = 144; pos & gt; = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
    ^
    Robot2:54: error: expected ‘;’ before ‘)’ token
    for (pos = 144; pos & gt; = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
    ^
    Robot2:199: error: expected ‘}’ at end of input
    }
    ^
    Multiple libraries were found for “AFMotor.h”
    Använd: /Users/franknelvig/Documents/Arduino/libraries/adafruit-Adafruit-Motor-Shield-library-99381df
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit_Motor_Shield_library
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit-Motor-Shield-library-master
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit_Motor_Shield_library
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit-Motor-Shield-library-master
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit_Motor_Shield_library
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit-Motor-Shield-library-master
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit_Motor_Shield_library
    Oanvänd: /Users/franknelvig/Documents/Arduino/libraries/Adafruit-Motor-Shield-library-master
    exit status 1
    ‘leftrightMotor_1KHZ’ was not declared in this scope

    This report would have more information with
    “Show verbose output during compilation”
    option enabled in File -> Preferences.

    Reply

    • Prithwiraj Bose

      |

      Are you still stuck with the problem? Please let me know.

      Reply

      • Prithwiraj Bose

        |

        Added a new section in the post:
        “COMPILATION ERROR ISSUE RESOLVED”

        Please read it.

        Reply

  • John

    |

    Could you please check your codes before uploading projects to the internet. In this code gt is an undeclared value, and users have to change many parts to make this code work. You wasted my time so much!

    Reply

    • Prithwiraj Bose

      |

      Oh! So, you wanted a place to copy from? Why don’t you keep a working copy yourself? Thanks for pointing out the compilation error, anyway I am not sorry for wasting anyone’s time.

      Reply

  • harun abubakar

    |

    the code is generating error i dont think it an open source code please respond of it is an open source code. want to try it if it really working

    Reply

    • Prithwiraj Bose

      |

      I don’t understand your question. The source code is given. What else are you expecting? Please let me know.

      Reply

    • Prithwiraj Bose

      |

      Added a new section in the post:
      “COMPILATION ERROR ISSUE RESOLVED”

      Please read it.

      Reply

  • karthik

    |

    this code when run shows Arduino: 1.6.5 (Windows 8.1), Board: “NodeMCU 1.0 (ESP-12E Module), 80 MHz, 115200, 4M (3M SPIFFS)”

    The sketch name had to be modified. Sketch names can only consist
    of ASCII characters and numbers (but cannot start with a number).
    They should also be less than 64 characters long.

    Build options changed, rebuilding all

    In file included from sketch_mar23c_23-03-17.ino:1:0:
    C:\Users\Admin\Documents\Arduino\libraries\libraries/AFMotor.h:156:47: error: ‘DC_MOTOR_PWM_RATE’ was not declared in this scope
    AF_DCMotor(uint8_t motornum, uint8_t freq = DC_MOTOR_PWM_RATE);
    ^
    sketch_mar23c_23-03-17:5: error: ‘A4’ was not declared in this scope
    sketch_mar23c_23-03-17.ino:12:15: note: in expansion of macro ‘TRIG_PIN’
    sketch_mar23c_23-03-17:6: error: ‘A5’ was not declared in this scope
    sketch_mar23c_23-03-17.ino:12:25: note: in expansion of macro ‘ECHO_PIN’
    sketch_mar23c_23-03-17:14: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
    sketch_mar23c_23-03-17:15: error: ‘leftrightMotor_1KHZ’ was not declared in this scope
    sketch_mar23c_23-03-17.ino: In function ‘void checkRoute()’:
    sketch_mar23c_23-03-17:54: error: ‘gt’ was not declared in this scope
    sketch_mar23c_23-03-17:54: error: expected primary-expression before ‘=’ token
    sketch_mar23c_23-03-17:54: error: expected ‘)’ before ‘;’ token
    sketch_mar23c_23-03-17:54: error: expected ‘;’ before ‘)’ token
    sketch_mar23c_23-03-17:199: error: expected ‘}’ at end of input
    Multiple libraries were found for “Servo.h”

    Used: C:\Users\Admin\AppData\Roaming\Arduino15\packages\esp8266\hardware\esp8266\2.3.0\libraries\Servo

    Not used: C:\Program Files (x86)\Arduino\libraries\Servo

    ‘A4’ was not declared in this scope

    This report would have more information with
    “Show verbose output during compilation”
    enabled in File > Preferences.

    Reply

    • Prithwiraj Bose

      |

      Will recheck. Please let me know if you still have the problem.

      Reply

    • Prithwiraj Bose

      |

      Added a new section in the post:
      “COMPILATION ERROR ISSUE RESOLVED”

      Please read it.

      Reply

  • richard chelsea

    |

    i like ur project but the code is giving me error like Arduino: 1.7.10 (Windows 7), Board: “Arduino Uno”

    Using library AFMotot.h in folder: C:\Users\User\Documents\Arduino\libraries\AFMotot.h (legacy)

    Using library Servo in folder: C:\Program Files\Arduino\libraries\Servo

    Using library NewPing in folder: C:\Program Files\Arduino\libraries\NewPing (legacy)

    C:\Program Files\Arduino/hardware/tools/avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=107010 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files\Arduino\hardware\arduino\avr\variants\standard -IC:\Users\User\Documents\Arduino\libraries\AFMotot.h -IC:\Program Files\Arduino\libraries\Servo\src -IC:\Program Files\Arduino\libraries\NewPing C:\Users\User\AppData\Local\Temp\build5326974962224778525.tmp\Arduino_Adafruit_RunAway_Robot.cpp -o C:\Users\User\AppData\Local\Temp\build5326974962224778525.tmp\Arduino_Adafruit_RunAway_Robot.cpp.o

    Arduino_Adafruit_RunAway_Robot.ino:14:25: error: ‘leftrightMotor_1KHZ’ was not declared in this scope

    Arduino_Adafruit_RunAway_Robot.ino:15:26: error: ‘leftrightMotor_1KHZ’ was not declared in this scope

    Error compiling.

    Reply

    • Prithwiraj Bose

      |

      Will recheck. Please let me know if you still have the problem.

      Reply

    • Prithwiraj Bose

      |

      Added a new section in the post:
      “COMPILATION ERROR ISSUE RESOLVED”

      Please read it.

      Reply

  • Prithwiraj Bose

    |

    Have you got the solution, or still looking for one? Please let me know, I’ll help.

    Reply

  • Destin

    |

    Your code is very helpful. It has an error so I can not run it. It says GT is not defined in this scope. However, I still appreciate it. It is well explained and I am using it to help me self-teach coding for an MFA project

    Reply

    • Prithwiraj Bose

      |

      Looks like when you copied the code, it was copied as HTML content not plain text. I do not find any ‘GT’ string in the code. so I guess it copied something like > which is not correct. Please refer the plain text code below. Copy from here to a plain text editor like Edit Plus or TextPad or Notepad or Notepad++

      #include <AFMotor.h>
      #include <Servo.h>
      #include <NewPing.h>

      #define TRIG_PIN A4 // Pin A4 on the Motor Drive Shield connected to the ultrasonic sensor
      #define ECHO_PIN A5 // Pin A5 on the Motor Drive Shield connected to the ultrasonic sensor
      #define MAX_DISTANCE_POSSIBLE 1000 // sets maximum useable sensor measuring distance to 1000cm
      #define MAX_SPEED 120 // sets speed of DC traction motors to 120/256 or about 47% of full speed – to reduce power draining.
      #define MOTORS_CALIBRATION_OFFSET 3 // this sets offset to allow for differences between the two DC motors
      #define COLL_DIST 20 // sets distance at which robot stops and reverses to 10cm
      #define TURN_DIST COLL_DIST+10 // sets distance at which robot looks away from object (not reverse) to 20cm (10+10)
      NewPing sonar(TRIG_PIN, ECHO_PIN, MAX_DISTANCE_POSSIBLE); // sets up sensor library to use the correct pins to measure distance.

      AF_DCMotor leftMotor(1, MOTOR12_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
      AF_DCMotor rightMotor(4, MOTOR34_1KHZ); // create motor #2, using M2 output, set to 1kHz PWM frequency
      Servo neckControllerServoMotor; // create servo object to control a servo

      int pos = 0; // this sets up variables for use in the sketch (code)
      int maxDist = 0;
      int maxAngle = 0;
      int maxRight = 0;
      int maxLeft = 0;
      int maxFront = 0;
      int course = 0;
      int curDist = 0;
      String motorSet = “”;
      int speedSet = 0;

      //——————————————– SETUP LOOP —————————————————————————-
      void setup() {
      neckControllerServoMotor.attach(9); // attaches the servo on pin 9 (SERVO_2 on the Motor Drive Shield to the servo object
      neckControllerServoMotor.write(90); // tells the servo to position at 90-degrees ie. facing forward.
      delay(2000); // delay for two seconds
      checkRoute(); // run the CheckRoute routine to find the best Route to begin travel
      motorSet = “FORWARD”; // set the director indicator variable to FORWARD
      neckControllerServoMotor.write(90); // ensure servo is still facing forward
      moveForward(); // run function to make robot move forward
      }
      //————————————————————————————————————————————

      //———————————————MAIN LOOP ——————————————————————————
      void loop() {
      checkForward(); // check that if the robot is supposed to be moving forward, that the drive motors are set to move forward – this is needed to overcome some issues with only using 4 AA NiMH batteries
      checkRoute(); // set ultrasonic sensor to scan for any possible obstacles
      }
      //————————————————————————————————————————————-
      void checkRoute() {
      int curLeft = 0;
      int curFront = 0;
      int curRight = 0;
      int curDist = 0;
      neckControllerServoMotor.write(144); // set servo to face left 54-degrees from forward
      delay(120); // wait 120milliseconds for servo to reach position
      for (pos = 144; pos > = 36; pos -= 18) // loop to sweep the servo (& sensor) from 144-degrees left to 36-degrees right at 18-degree intervals.
      {
      neckControllerServoMotor.write(pos); // tell servo to go to position in variable ‘pos’
      delay(90); // wait 90ms for servo to get to position
      checkForward(); // check the robot is still moving forward
      curDist = readPing(); // get the current distance to any object in front of sensor
      if (curDist < COLL_DIST) { // if the current distance to object is less than the collision distance
      checkCourse(); // run the checkCourse function
      break; // jump out of this loop
      }
      if (curDist < TURN_DIST) { // if current distance is less than the turn distance
      changeRoute(); // run the changeRoute function
      }
      if (curDist > curDist) {
      maxAngle = pos;
      }
      if (pos > 90 && curDist > curLeft) {
      curLeft = curDist;
      }
      if (pos == 90 && curDist > curFront) {
      curFront = curDist;
      }
      if (pos < 90 && curDist > curRight) {
      curRight = curDist;
      }
      }
      maxLeft = curLeft;
      maxRight = curRight;
      maxFront = curFront;
      }
      //————————————————————————————————————————————-
      void setCourse() { // set direction for travel based on a very basic distance map, simply which direction has the greatest distance to and object – turning right or left?
      if (maxAngle < 90) {
      turnRight();
      }
      if (maxAngle > 90) {
      turnLeft();
      }
      maxLeft = 0;
      maxRight = 0;
      maxFront = 0;
      }
      //————————————————————————————————————————————-
      void checkCourse() { // we’re about to hit something so move backwards, stop, find where the empty Route is.
      moveBackward();
      delay(500);
      moveStop();
      setCourse();
      }
      //————————————————————————————————————————————-
      void changeRoute() {
      if (pos < 90) {
      lookLeft(); // when current position of sensor is less than 90-degrees, it means the object is on the right hand side so look left
      }
      if (pos > 90) {
      lookRight(); // when current position of sensor is greater than 90-degrees, it means the object is on the left hand side so look right
      }
      }
      //————————————————————————————————————————————-

      int readPing() { // read the ultrasonic sensor distance
      delay(70);
      unsigned int uS = sonar.ping();
      int cm = uS / US_ROUNDTRIP_CM;
      return cm;
      }
      //————————————————————————————————————————————-
      void checkForward() {
      if (motorSet == “FORWARD”) {
      leftMotor.run(FORWARD); // ensure motors are going forward
      rightMotor.run(FORWARD);
      }
      }
      //————————————————————————————————————————————-
      void checkBackward() {
      if (motorSet == “BACKWARD”) {
      leftMotor.run(BACKWARD); // ensure motors are going backward
      rightMotor.run(BACKWARD);
      }
      }
      //————————————————————————————————————————————-

      // In some cases, the Motor Drive Shield may just stop if the supply voltage is too low (due to using only four NiMH AA cells).
      // The above functions simply remind the Shield that if it’s supposed to go forward, then ensure it is going forward and vice versa.

      //————————————————————————————————————————————-
      void moveStop() {
      leftMotor.run(RELEASE); // stop the motors.
      rightMotor.run(RELEASE);
      }
      //————————————————————————————————————————————-
      void moveForward() {
      motorSet = “FORWARD”;
      leftMotor.run(FORWARD); // turn it on going forward
      rightMotor.run(FORWARD); // turn it on going forward
      for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
      {
      leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
      rightMotor.setSpeed(speedSet);
      delay(5);
      }
      }
      //————————————————————————————————————————————-
      void moveBackward() {
      motorSet = “BACKWARD”;
      leftMotor.run(BACKWARD); // turn it on going forward
      rightMotor.run(BACKWARD); // turn it on going forward
      for (speedSet = 0; speedSet < MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
      {
      leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
      rightMotor.setSpeed(speedSet);
      delay(5);
      }
      }
      //————————————————————————————————————————————-
      void turnRight() {
      motorSet = “RIGHT”;
      leftMotor.run(FORWARD); // turn motor 1 forward
      rightMotor.run(BACKWARD); // turn motor 2 backward
      delay(400); // run motors this way for 400ms
      motorSet = “FORWARD”;
      leftMotor.run(FORWARD); // set both motors back to forward
      rightMotor.run(FORWARD);
      }
      //————————————————————————————————————————————-
      void turnLeft() {
      motorSet = “LEFT”;
      leftMotor.run(BACKWARD); // turn motor 1 backward
      rightMotor.run(FORWARD); // turn motor 2 forward
      delay(400); // run motors this way for 400ms
      motorSet = “FORWARD”;
      leftMotor.run(FORWARD); // turn it on going forward
      rightMotor.run(FORWARD); // turn it on going forward
      }
      //————————————————————————————————————————————-
      void lookRight() {
      rightMotor.run(BACKWARD); // looking right? set right motor backwards for 400ms
      delay(400);
      rightMotor.run(FORWARD);
      }
      //————————————————————————————————————————————-
      void lookLeft() {
      leftMotor.run(BACKWARD); // looking left? set left motor backwards for 400ms
      delay(400);
      leftMotor.run(FORWARD);
      }

      Reply

    • Prithwiraj Bose

      |

      Sorry Destin. I was wrong – the code in the blog page indeed had the ‘gt’ string. I’ve corrected it and also pasted the correct one in the previous comment. Please refer this code. Thanks for pointing out the issue.

      Reply

  • judibolanet.com

    |

    Hello are using WordPress for your site platform? I’m new to the blog world but I’m trying to get
    started and create my own. Do you need any coding expertise
    to make your own blog? Any help would be greatly appreciated!

    Reply

    • Prithwiraj Bose

      |

      I do see that you have bad SEO skills. Why not work on that one first? 🙂

      Reply

Leave a comment

%d bloggers like this: