• me

  • IMG_3003

  • IMG_3011

  • IMG_3260

  • sribasu.com-wallpaper

  • prithwiraj-ishita

  • Prithwiraj_Bose

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

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 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 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

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 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.


Adafruit Motor Shield is really a wonderful board to build Arduino based robots. 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 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 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 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, leftrightMotor_1KHZ); // create motor #1 using M1 output on Motor Drive Shield, set to 1kHz PWM frequency
AF_DCMotor rightMotor(4, leftrightMotor_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 & gt; = 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 & lt; 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 & lt; TURN_DIST) { // if current distance is less than the turn distance
      changeRoute(); // run the changeRoute function
    if (curDist & gt; curDist) {
      maxAngle = pos;
    if (pos & gt; 90 & amp; & curDist & gt; curLeft) {
      curLeft = curDist;
    if (pos == 90 & amp; & curDist & gt; curFront) {
      curFront = curDist;
    if (pos & lt; 90 & amp; & curDist & gt; 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 & lt; 90) {
  if (maxAngle & gt; 90) {
  maxLeft = 0;
  maxRight = 0;
  maxFront = 0;
void checkCourse() { // we're about to hit something so move backwards, stop, find where the empty Route is.
void changeRoute() {
  if (pos & lt; 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 & gt; 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
  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
void checkBackward() {
  if (motorSet == "BACKWARD") {
    leftMotor.run(BACKWARD);  // ensure motors are going 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.
void moveForward() {
  motorSet = "FORWARD";
  leftMotor.run(FORWARD);      // turn it on going forward
  rightMotor.run(FORWARD);      // turn it on going forward
  for (speedSet = 0; speedSet & lt; MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
    leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
void moveBackward() {
  motorSet = "BACKWARD";
  leftMotor.run(BACKWARD);      // turn it on going forward
  rightMotor.run(BACKWARD);     // turn it on going forward
  for (speedSet = 0; speedSet & lt; MAX_SPEED; speedSet += 2) // slowly bring the speed up to avoid loading down the batteries too quickly
    leftMotor.setSpeed(speedSet + MOTORS_CALIBRATION_OFFSET);
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
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
void lookLeft() {
  leftMotor.run(BACKWARD);  // looking left? set left motor backwards for 400ms


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 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 Robot and the way it deals with obstacles.



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


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 Robot looks like. See the video and the images of my Robot below, it works perfectly.



Different Types of Gold Fishes

Written by Prithwiraj Bose on . Posted in Hobby Centre

This video depicts various breeds of Gold Fishes.

ত্রাতা (কবিতা)

Written by Prithwiraj Bose on . Posted in Time, Society and Politics

বৈশাখী ঝঞ্ঝায়
আলো নেভা রাতে
ঘুমানো শহরতলি
আধ-পেট ভাতে

ব্রিগেডে বিপ্লবে
ভোটের বাজারে
শুকিয়ে শুকনো হওয়া
হাজারে হাজারে

অহেতুক আশ্বাসে
তর্ক আসরে
সদ্য ঠকিয়ে যাওয়া
পুরনো দোসরে

চাষের জমিতে
শ্রমিকের চেতনা
তুমি এনে দিলে।

Link A Particular Moment / Scene in Youtube Video (Hyperlink to Minutes and Seconds)

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

Youtube Videos can be embedded on various devices, web pages and platforms. Youtube provides lot of easy to use features to embed and hyperlink videos. One of such cool features are – you can even link a particular moment/scene in a Youtube Video.

Problem of Video Categories Section Fixed : WordPress Video Plugin

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

Now the problem of the Video Categories and Popular/Latest Videos etc is fixed. Your can watch videos by categories on sribasu.com

I had an issue with the WordPress Video Gallery Plugin. The Video Categories page was getting redirected to Blog Categories page.  Finally I got the solution to this problem from WordPress Support forum.
%d bloggers like this: