How To Make an Obstacle Avoiding Arduino Robot

 by generalgeek314
Featured

Step 10: Wiring and Completion!

20120211_215212.jpg
20120211_212752.jpg
20120211_212843.jpg
20120211_213641.jpg
20120211_214329.jpg
20120211_214343.jpg
20120211_214348.jpg
20120211_215050.jpg
20120211_215111.jpg
20120211_215120.jpg
20120211_215126.jpg
Now, time to wire everything up, download the program, and test her out! 

I'll tell you how everything is connected one component at a time. Refer to the pictures to get a better idea of how it should look (if it's a rats nest of wires... you're on the right track). 

Motor battery: Hook up positive and negative to the positive and negative power rails on the far side of the breadboard (see picture 2).
Grounds: Take a jumper wire and attach the grounds of both power rails together (see picture 3). IMPORTANT, DON'T FORGET
5 volt power supply: Attach a jumper from 5V on the Arduino to the power rail on the breaboard closest to the Arduino.
Servo motors: Attach the left motor with the red and black wires going to the 5 volt power rail and ground respectively. Then, attach the white wire of the left servo to pin 10, the right one to pin 11, and the PING))) sensor panning servo to pin 6.
PING))) sensor: Either use the included cable and attach male-to-male jumpers to that, or use separate male-to-female jumpers to make the following connections: connect the pin on the PING))) that says 5V to the 5 volt rail... connect the pin that is labelled GND to either ground rail... and finally connect the one labelled "SIG" to pin 7 on the Arduino. 

I think that's everything... well, if it doesn't work you can yell at me in the comments because I probably forgot something. The wiring will look like a total rats nest, if you want it to look a little neater you can use male to male header pins like the setup I used in the video.
UPDATE: I have made a mistake, thanks to faroos7 for pointing it out! Also, in the code you'll notice a variable named irPin, which is set to 0. That's part of another project, and you can feel free to delete that variable. 

To get her going, download the attached Arduino program, run it, and it should have behavior similar to that in the video at the beginning of this Instructable. If it works, congratulations, you're done! If not, tell me the problem in the comments and I'll do my best to help you. 

If you want to do more experiments with Arduino on the breadboard, check out sciguy14's Arduino tutorials on Youtube! They're very well done, and they're how I learned originally. http://www.youtube.com/playlist?list=PLA567CE235D39FA84&feature=plcp

I hope my Instructable helped you, this is my first one and so I appreciate any feedback you can give. Please vote for me in the Arduino contest as well! Bye!
 
Remove these adsRemove these ads by Signing Up
paleontologist99 says: Apr 13, 2013. 5:02 PM
can you also put the center servo code
paleontologist99 says: Mar 21, 2013. 8:31 PM
hey can you put the code in the comments because I'm having a hard time opening the code attachment
generalgeek314 (author) in reply to paleontologist99Mar 25, 2013. 6:44 PM
Sorry it took me so long to reply

/*MAEP 2.0 Navigation
by Noah Moroze, aka GeneralGeek
This code has been released under a Attribution-NonCommercial-ShareAlike license, more info at http://creativecommons.org/licenses/
PING))) code by David A. Mellis and Tom Igoe http://www.arduino.cc/en/Tutorial/Ping
*/

#include <Servo.h> //include Servo library

const int RForward = 0;
const int RBackward = 180;
const int LForward = RBackward;
const int LBackward = RForward;
const int RNeutral = 90;
const int LNeutral = 90; //constants for motor speed
const int pingPin = 7;
const int irPin = 0;  //Sharp infrared sensor pin
const int dangerThresh = 10; //threshold for obstacles (in cm)
int leftDistance, rightDistance; //distances on either side
Servo panMotor; 
Servo leftMotor;
Servo rightMotor; //declare motors
long duration; //time it takes to recieve PING))) signal

void setup()
{
  rightMotor.attach(11);
  leftMotor.attach(10);
  panMotor.attach(6); //attach motors to proper pins
  panMotor.write(90); //set PING))) pan to center
}

void loop()
{
  int distanceFwd = ping();
  if (distanceFwd>dangerThresh) //if path is clear
  {
    leftMotor.write(LForward);
    rightMotor.write(RForward); //move forward
  }
  else //if path is blocked
  {
    leftMotor.write(LNeutral);
    rightMotor.write(RNeutral);
    panMotor.write(0);
    delay(500);
    rightDistance = ping(); //scan to the right
    delay(500);
    panMotor.write(180);
    delay(700);
    leftDistance = ping(); //scan to the left
    delay(500);
    panMotor.write(90); //return to center
    delay(100);
    compareDistance();
  }
}
 
void compareDistance()
{
  if (leftDistance>rightDistance) //if left is less obstructed
  {
    leftMotor.write(LBackward);
    rightMotor.write(RForward); //turn left
    delay(500);
  }
  else if (rightDistance>leftDistance) //if right is less obstructed
  {
    leftMotor.write(LForward);
    rightMotor.write(RBackward); //turn right
    delay(500);
  }
   else //if they are equally obstructed
  {
    leftMotor.write(LForward);
    rightMotor.write(RBackward); //turn 180 degrees
    delay(1000);
  }
}

long ping()
{
  // Send out PING))) signal pulse
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
 
  //Get duration it takes to receive echo
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);
 
  //Convert duration into distance
  return duration / 29 / 2;
}
greentree89 says: Mar 13, 2012. 8:22 PM
Hey there i am back, i finally got all the parts and i have put my robot together, all that is left is to wire it up! :)
Just got a quick question, I am not entirely sure about the 5v power rail you mentioned.
So i got the 3 servo motors and the ping sensor that all need 5v.
should i be connecting them all to the battery 5v rail or the arduino 5v rail that you said to connect to the breadboard?
Thanks again !
generalgeek314 (author) in reply to greentree89Mar 14, 2012. 1:04 PM
Hi, I'm glad that the robot build went successfully!
Wire up the 3 servo motors to power from the separate battery. Motors use up a lot of current, more than the regulator on the Arduino provides, and they can't be powered directly from the 9V battery because 9 volts is too much for them. That's why you have to hook them up to the other battery.
As for the sensor, hook that up to 5V power from the Arduino. It needs the same steady voltage the Arduino is getting in order to give accurate results.
Hope I helped. If things are still unclear, feel free to ask and I'll do my best to fix whatever comes up.
simmarkalsi in reply to generalgeek314Feb 1, 2013. 7:11 AM
hey i too much liked the project and i would like to try it once but THERE WAS A PROBLEM WITH SERVO MOTORS I DONT KNOW HOW TO MOD SERVO MOTORS FOR CONTINUOUS ROTATION could you please send me message telling me how to do it or a link ...................... please!!!
generalgeek314 (author) in reply to simmarkalsiFeb 6, 2013. 5:16 PM
Also, for step 1 of that tutorial keep in mind that the code provided in the calibrating servos step will work to put the servos in the center position.
generalgeek314 (author) in reply to simmarkalsiFeb 6, 2013. 5:12 PM
Depending on the type of servo you have, you can Google for the solution. Although the process is generally similar amongst all servos, it may vary so I can't give one link that will teach you how to do it. This is a pretty good tutorial though - http://www.societyofrobots.com/actuators_modifyservo.shtml
greentree89 in reply to generalgeek314Mar 14, 2012. 4:00 PM
Hey thanks for your reply, i have now wired it and uploaded the code to my robot.
What happens however is that it rotates in a circle with the right motor moving forward and the left moving backward.
when i put my hand in front of the sensor it moves backwards untill all is clear and then continues to move in rotation, also the sensor servo does not operate at all.

I made sure i got all the wires in the right place and also tried swapping the motor wires around but just got more odd movements

here is the code i am using:
/*MAEP 2.0 Navigation
by Noah Moroze, aka GeneralGeek
This code has been released under a Attribution-NonCommercial-ShareAlike license, more info at http://creativecommons.org/licenses/
PING))) code by David A. Mellis and Tom Igoe http://www.arduino.cc/en/Tutorial/Ping
*/

#include //include Servo library
#include

Ultrasonic ultrasonic ( 4, 5);
const int RForward = 0;
const int RBackward = 180;
const int LForward = RBackward;
const int LBackward = RForward;
const int RNeutral = 90;
const int LNeutral = 90; //constants for motor speed
const int irPin = 0; //Sharp infrared sensor pin
const int dangerThresh = 4; //threshold for obstacles (in inches)
int leftDistance, rightDistance; //distances on either side
Servo panMotor;
Servo leftMotor;
Servo rightMotor; //declare motors

void setup()
{
rightMotor.attach(11);
leftMotor.attach(10);
panMotor.attach(6); //attach motors to proper pins
panMotor.write(90); //set PING))) pan to center
leftMotor.write(90);
rightMotor.write(90);
}

void loop()
{
int distanceFwd = ultrasonic.Ranging(INC);
if (distanceFwd>dangerThresh) //if path is clear
{
leftMotor.write(LForward);
rightMotor.write(RForward); //move forward
}
else //if path is blocked
{
leftMotor.write(LNeutral);
rightMotor.write(RNeutral);
panMotor.write(0);
delay(500);
rightDistance = ultrasonic.Ranging(INC); //scan to the right
delay(500);
panMotor.write(180);
delay(700);
leftDistance = ultrasonic.Ranging(INC); //scan to the left
delay(500);
panMotor.write(90); //return to center
delay(100);
compareDistance();
}
}

void compareDistance()
{
if (leftDistance>rightDistance) //if left is less obstructed
{
leftMotor.write(LBackward);
rightMotor.write(RForward); //turn left
delay(500);
}
else if (rightDistance>leftDistance) //if right is less obstructed
{
leftMotor.write(LForward);
rightMotor.write(RBackward); //turn right
delay(500);
}
else //if they are equally obstructed
{
leftMotor.write(LForward);
rightMotor.write(RBackward); //turn 180 degrees
delay(1000);
}
}

gasconmarvinlogico in reply to greentree89Jan 27, 2013. 2:52 AM
hello @greentree89 thanks for the code.. you help me a lot.. we have the same number of pins. if you don't mind, do you still have the schematic diagram or the wiring diagram? coz i'm a beginner if in wiring the arduino. i'm hoping that you can share me the wiring diagram.. thank very much.
generalgeek314 (author) in reply to greentree89Mar 14, 2012. 4:11 PM
For your servo direction problem, try changing this in the code:
const int LForward = RBackward;
const int LBackward = RForward;
To this:
const int LForward = 0;
const int LBackward = 180;

As for your sensor servo, I'm not sure what the problem is. Are you certain this servo works? Try using code from this tutorial to test it - http://arduino.cc/it/Tutorial/Sweep
greentree89 in reply to generalgeek314Mar 15, 2012. 7:46 PM
I fixed it! :D
I was reading up the reason for the odd behavior from all 3 servos and it turns out it was because the servos need to share the ground from both arduino and the battery, i must of missed that part on your tutorial, i just took a lead from from the arduino gnd and connected it to the breadbord gnd rail that you said to link from both sides.
now it responds perfectly! :)
I have now tested out the whole code as i was breaking it down to see how it responded.
everything seems fine except the panmotor still moves all the way to the right at the very start before it even detects an object.
i will do some more tests tomorrow to find out the problem.
generalgeek314 (author) in reply to greentree89Mar 16, 2012. 4:13 AM
Great! Glad to see you were able to find a solution for that problem on your own :) For the problem with the panning servo, try do step 2 again with just that servo (after taking the servo "horn" with the ping sensor on it off). After you've centered the servo, put the ping sensor back on so that it's facing forward.
greentree89 in reply to generalgeek314Mar 17, 2012. 2:40 PM
Hey i tried everything to get the panmotor servo working correctly but it will not respond other than go clockwise then it starts shaking, very odd i can only say it must be faulty.
i will order a new servo but in the mean time i have simplified the code for a fixed sensor so it simply turns left on detection of obstacles, i have also added a piezo and led to the code, i will make a video to show you my robot :)
it is very simple compared to your robot but for my first robot i am very proud :D
i also had to increase the speed of the right servo as it seems to turn left, i must of designed the balance of the chassis badly.
i also find that when it is heading towards obstacles at an angle it does not pick up on the obstacle and completely gets stuck, but i do have a spare sensor, perhaps i can use 2 on the robot to help this.
well theres plenty of ideas to upgrade my robot :)
I will make the video of my robot very soon, thankyou so much for all your help, you've been amazing and so very helpful :)
generalgeek314 (author) in reply to greentree89Mar 18, 2012. 9:12 AM
It's too bad your servo isn't working, but I'm glad you've got your robot working anyways! I look forward to seeing it, and I like that you've added your own custom additions with the LED and piezo. Maybe to give it a more interesting behavior you could have it turn randomly when it detects an obstacle? Try looking here: http://arduino.cc/en/Reference/random

I hope you continue with this hobby, it's very fun and I'm incredibly happy to have helped you enter the world of robotics. I recommend you check out letsmakerobots.com, they have a great community of robot builders that give great advice and feedback, and also there are lots of robots there to get inspiration from.
greentree89 in reply to generalgeek314Mar 18, 2012. 7:55 PM
Hey there! :)
Thankyou so much for all your encouragement and it is because of you i have built my first robot.
I built up a random code from the link you sent me, it works great!
And to add to that i combined the code with something else i found which solves a problem my robot had,

from my last post, simply when the robot came in at an obstacle from an angle it would not detect it and then try and turn too late and it must move forward to make a turn, but when it gets too close to an obstacle it moves backwards then turns.
I have tested the random turning which i really like but i noticed a problem i had not thought of before,

lets say it comes to a corner, and chooses to turn left, it will then immediately meet the other wall and by chance the random code makes it turn right it hit the previous wall again, i have watched it do this quite a few times, but its still quite fun to watch it like this as you said because you never know which turn it will take making things interesting, it always gets it's self out of areas sooner or later anyway hahah

I have bought a new servo for the sensor which should arrive shortly.
Video coming soon! :)
Thanks again!
here is my code if you are interested in seeing it at the moment:


#include //include Servo library
#include

Ultrasonic ultrasonic ( 4, 5);


const int numOfReadings = 1; // number of readings to take/ items in the array
int readings[numOfReadings]; // stores the distance readings in an array
int arrayIndex = 0; // arrayIndex of the current item in the array
int total = 0; // stores the cumlative total
int averageDistance = 0; // stores the average value
int echoPin = 5; // SRF05 echo pin (digital 2)
int initPin = 4; // SRF05 trigger pin (digital 3)
unsigned long pulseTime = 0; // stores the pulse in Micro Seconds
unsigned long distance = 0; // variable for storing the distance (cm
int pinSpeaker = 13;
const int RForward = 0;
const int RBackward = 180;
const int LForward = RBackward;
const int LBackward = RForward;
const int RNeutral = 90;
const int LNeutral = 90; //constants for motor speed
int leftDistance, rightDistance; //distances on either side
Servo leftMotor;
Servo rightMotor; //declare motors
int randNumberSpeed; // variable to store the random speed value
int randNumberDir; // variable to store the random direction value
int x = randNumberDir;
void setup()
{
Serial.begin(9600);
rightMotor.attach(11);
leftMotor.attach(8);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(pinSpeaker, OUTPUT);
pinMode(4, OUTPUT); // trig init
pinMode(5, INPUT); //echo
// create array loop to iterate over every item in the array

for (int thisReading = 0; thisReading < numOfReadings; thisReading++) {
readings[thisReading] = 0;

randomSeed(millis());
}

}

void loop() {
digitalWrite(initPin, HIGH); // send 10 microsecond pulse
delayMicroseconds(10); // wait 10 microseconds before turning off
digitalWrite(initPin, LOW); // stop sending the pulse
pulseTime = pulseIn(echoPin, HIGH); // Look for a return pulse, it should be high as the pulse goes low-high-low
distance = pulseTime/58; // Distance = pulse time / 58 to convert to cm.
total= total - readings[arrayIndex]; // subtract the last distance
readings[arrayIndex] = distance; // add distance reading to array
total= total + readings[arrayIndex]; // add the reading to the total
arrayIndex = arrayIndex + 1; // go to the next item in the array

// At the end of the array (10 items) then start again
if (arrayIndex >= numOfReadings) {
arrayIndex = 0;
}

averageDistance = total / numOfReadings; // calculate the average distance
delay(10);

// Check the average distance and move accordingly

if (averageDistance <= 10) {
// go backwards
leftMotor.writeMicroseconds(1000);
rightMotor.writeMicroseconds(2000);
digitalWrite(2, HIGH);
digitalWrite(3, LOW);
{
playTone(750, 500);
delay(350);
}
}


if (averageDistance <= 25 && averageDistance > 10 ) {

//turn left
randomSeed(millis());
randNumberDir = random(300); {
if (randNumberDir > 150){
rightMotor.writeMicroseconds(1000);
leftMotor.writeMicroseconds(1500);
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
{
playTone(750, 300);
delay(750);
}
}
else if (randNumberDir < 150){
rightMotor.writeMicroseconds(1500);
leftMotor.writeMicroseconds(2000);
digitalWrite(2, LOW);
digitalWrite(3, HIGH);
{
playTone(750, 400);
delay(750);
}
}
}
}

if (averageDistance > 25) {
// go forward
digitalWrite(2, LOW);
digitalWrite(3, LOW);
delay(1000);
leftMotor.writeMicroseconds(2000);
rightMotor.writeMicroseconds(1100);
}
}


// duration in mSecs, frequency in hertz
void playTone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);
}
}
greentree89 in reply to generalgeek314Mar 14, 2012. 6:38 PM
Heheh got 3 problems all at once, i tried this but it still does the same thing.
It simply continues to move in rotation, it seems to be the left motor that is going the wrong way no matter where ever i set it to 0, 180 or 90

And of course it does not stop but rather instead moves backwards when there is an obstacle.

I also tried that code for the sensor servo, it moves it all the way to the right but then nothing else happens, same for the robot code, nothing moves it to the left again.

Its ok if you cant figure this one out, you've been an amazing help with all my questions, i will continue to try and work on it.
Thanks again.
gasconmarvinlogico says: Jan 21, 2013. 3:54 AM
thank you very much for your reply.. i will message if i will start doing the project, because im still waiting the components... can i ask you a question on how to send a message using an arduino and receive it using arduino also.. your reply helps a lot..
generalgeek314 (author) in reply to gasconmarvinlogicoJan 26, 2013. 12:48 PM
There are many ways to make two arduinos communicate - if you want wireless, I might take a look at bluetooth or xbee. If you are okay with a wired connection, I would try serial. Here's an example of serial that you can start from - http://www.billporter.info/2011/05/30/easytransfer-arduino-library/. Google is your friend to get more info :)
gasconmarvinlogico says: Jan 24, 2013. 7:56 AM
hello good day.. im already starting to build the robot but i have a problem of my sensor because it has a 4 pins output the ( VCC , trig(T), echo(R), GND), whereas your sensor has only 3 pins,, how should i make it to work...?? please help me...hoping for your immediate reply..
generalgeek314 (author) in reply to gasconmarvinlogicoJan 26, 2013. 12:45 PM
If you go the next comment page, at the very bottom you can take a look at a discussion I had with user "greentree". He has the same type of sensor as you, and he managed to make it work.
gasconmarvinlogico says: Jan 15, 2013. 2:44 AM
hello.. your project is awesome.i'm a beginner about arduino.. i want to try how it really works but i'm a little confuse how to connect the wires.. can you help me?? i already have the components.. do you have clear wiring diagram?? I'm looking forward for your immediate reply... please help me...
generalgeek314 (author) in reply to gasconmarvinlogicoJan 20, 2013. 8:20 PM
Hi, I'm so sorry I didn't reply sooner; I've been busy lately. Unfortunately I took this robot apart a while ago to scrap some components for other projects... just try to follow the instructions given carefully step by step. If you're confused about any one particular step, just message me/comment and I'll do my best to help :)
greentree89 says: Feb 25, 2012. 5:37 PM
I found this: http://www.meanpc.com/2012/01/hc-sr04-ultrasonic-sensor-added-to.html
though i much prefer your code where the ping servo rotates to choose the best path.
I shall now try and combine both codes to suit my robot :)
generalgeek314 (author) in reply to greentree89Feb 26, 2012. 6:58 AM
Sorry, I made a slight mistake. As well as replacing int distanceFwd = ping();, you have to replace all uses of "ping()" with "ultrasonic.Ranging(CM)".
greentree89 in reply to generalgeek314Feb 26, 2012. 7:35 PM
Hey this is great! thankyou very much.

I spent a while trying to combine the codes but i kept getting so many errors but after i tried what you sent me, it works perfectly.
Just wondering do i change the Ranging(CM) to an actual number like Ranging(15) ? just to be sure.

I have just ordered the right batteries and i must also get a new servo motor as for some reason it gets really hot but it no longer moves.

I will be sure to upload photo's and a vid to show you :)
Thanks again.
generalgeek314 (author) in reply to greentree89Feb 27, 2012. 4:12 AM
No problem, I'm happy to help. No, you don't change Ranging(CM) to an actual number, it means you want to get the value of the distance away something is in centimeters. You could do Ranging(IN) instead, which would give you the distance in inches. You could use that in my code if you wanted, as long as you changed what the variable dangerThresh is in the beginning to how far away you want something to be in inches when the robot stops and turns. I hope you get your parts soon!
generalgeek314 (author) in reply to greentree89Feb 25, 2012. 6:32 PM
Good luck! I have done so more research, and I think I can help you specifically.
In the beginning, with all the variables, you want to create your ultrasonic sensor. Declare it like this: Ultrasonic ultrasonic( trigPin, echoPin);
Of course, make trigPin and echoPin whatever pins you plugged them into on the Arduino. Now, this library is actually quite handy, so you can delete the whole ping() function I wrote. Find the code that looks like:
void ping()
{
some stuff in here
}
and delete all that. Then, where it says int distanceFwd = ping();, change it to say int distanceFwd = ultrasonic.Ranging(CM);

Good luck, and feel free to ask if you need any more help. I'd like to see your robot when you finish, so if you could post pics/a video of it online that would be nice :)
greentree89 says: Feb 24, 2012. 3:45 PM
Hey my ultrasonic sensor has 4 pins, the 5v, gnd, echo and trig.
How should i connect them and what should i add to the code to make it work?
Thanks :)
generalgeek314 (author) in reply to greentree89Feb 24, 2012. 5:14 PM
Hi,
I haven't used a sensor like that myself, so I can't give any personal help. However, this link has some useful information on how to use it with Arduino: http://letsmakerobots.com/node/30209. I'm not sure what your level of experience is, because unfortunately the link I provided doesn't go into much detail about what to do. If you need more help, just ask and I'll do what I can.
greentree89 in reply to generalgeek314Feb 25, 2012. 1:22 PM
Hey thanks for your reply and link, i have tried combining the code with your one but i am very new with programming and it does not take long for me to get lost.
I am not sure what i should take out of your code and replace.
Pro

Get More Out of Instructables

Already have an Account?

close

PDF Downloads
As a Pro member, you will gain access to download any Instructable in the PDF format. You also have the ability to customize your PDF download.

Upgrade to Pro today!