Ping Sensor and Led use

Hey guys,

I was wondering if you could offer advice.

I have built the avoidance robot.

I would now like to add to it.

I would like to add leds and 

possibly a speaker, so when the 

robot approaches a wall maybe the leds turn on. When it reverses maybe it beeps.

How would I do this.?

How do I incorperate it into the code. 

By this I mean say for example

If ping distance is less then 5cm then: led on

type of thing?

My coding is practically non existant. I am still learning

and bit by bit understanding.

Thanks guys.

 

 

#define LeftMotorForward 8

#define LeftMotorBackward 9

#define RightMotorForward 10

#define RightMotorBackward 11

#define USTrigger 3

#define USEcho 2

#define MaxDistance 100

#define LED 13

 

//Here we have created two 'objects', one for the servo and one for the ultrasonic sensor

Servo servo;

NewPing sonar(USTrigger, USEcho, MaxDistance);

 

//Below we are creating unsigned integer variables which we will use later on in the code. They are unsigned as they will only have postive values

unsigned int duration;

unsigned int distance;

unsigned int FrontDistance;

unsigned int LeftDistance;

unsigned int RightDistance;

unsigned int Time;

unsigned int CollisionCounter;

 

void setup()                                            //This block happens once on startup

{

  Serial.begin(9600);                              //I have included the serial initialize but commented it out, if you want to debug and print information to the serial monitor just uncomment

 

  //Here we are setting the pin modes. As we will sending out signals from the pins we set them as outputs

  pinMode(LeftMotorForward, OUTPUT);

  pinMode(LeftMotorBackward, OUTPUT);

  pinMode(RightMotorForward, OUTPUT);

  pinMode(RightMotorBackward, OUTPUT);

  pinMode(LED, OUTPUT);

  servo.attach(6);                                    //The servo is attached to pin 4

}

 

void loop()                                           //This block repeats itself while the Arduino is turned on

{

  servo.write(90);                                    //Rotate the servo to face the front                  

  scan();                                             //Go to the scan function

  FrontDistance = distance;                           //Set the variable FrontDistance to the value of the distance returned from the scan function

  Serial.println("Front distance = ");

  Serial.print(distance);

  if(FrontDistance > 40 || FrontDistance == 0)        //If there is nothing infront of the robot within 40cm or the distance value is 0 (which for the newping libary means no ping was returned) then...

  {

   moveForward();                                     //Go to the moveForward function

  } 

  else                                                //Else (if there is something infront of the robot within 40cm) then...

  {

    CollisionCounter = CollisionCounter + 1;

    moveStop();                                       //Go to the moveStop function

    navigate();

  }

}

 

void moveForward()                                    //This function tells the robot to go forward 

{

  Serial.println("");

  Serial.println("Moving forward");

  digitalWrite(LeftMotorBackward, LOW);

  digitalWrite(LeftMotorForward, HIGH);

  digitalWrite(RightMotorBackward, LOW);

  digitalWrite(RightMotorForward, HIGH);

}

 

void moveBackward()                                  //This function tells the robot to move backward

{

  Serial.println("");

  Serial.println("Moving backward");

  digitalWrite(LeftMotorForward, LOW);

  digitalWrite(LeftMotorBackward, HIGH);

  digitalWrite(RightMotorForward, LOW);

  digitalWrite(RightMotorBackward, HIGH);

}

 

void moveLeft()                                      //This function tells the robot to turn left

{

  Serial.println("");

  Serial.println("Moving left");

  digitalWrite(LeftMotorForward, LOW);

  digitalWrite(LeftMotorBackward, HIGH);

  digitalWrite(RightMotorBackward, LOW);

  digitalWrite(RightMotorForward, HIGH);

 

}

 

void moveRight()                                    //This function tells the robot to turn right

{

  Serial.println("");

  Serial.println("Moving right");

  digitalWrite(LeftMotorBackward, LOW);

  digitalWrite(LeftMotorForward, HIGH);

  digitalWrite(RightMotorForward, LOW);

  digitalWrite(RightMotorBackward, HIGH);

}

 

void moveStop()                                     //This function tells the robot to stop moving

{

  Serial.println("");

  Serial.println("Stopping");

  digitalWrite(LeftMotorBackward, LOW);

  digitalWrite(LeftMotorForward, LOW);

  digitalWrite(RightMotorForward, LOW);

  digitalWrite(RightMotorBackward, LOW);

}

void scan()                                         //This function determines the distance things are away from the ultrasonic sensor

{

  Serial.println("");

  Serial.println("Scanning");

  Time = sonar.ping(); 

  distance = Time / US_ROUNDTRIP_CM;

  delay(500);

}

void navigate()

{

    Serial.println("There's an obstacle!");

    servo.write(167);                                 //Move the servo to the left (my little servos didn't like going to 180 so I played around with the value until it worked nicely)

    delay(1000);                                       //Wait half a second for the servo to get there

    scan();                                           //Go to the scan function

    LeftDistance = distance;                          //Set the variable LeftDistance to the distance on the left

    Serial.println("Left distance = ");

    Serial.print(distance);

    servo.write(0);                                   //Move the servo to the right

    delay(1000);                                       //Wait half a second for the servo to get there

    scan();                                           //Go to the scan function

    RightDistance = distance;                         //Set the variable RightDistance to the distance on the right

    Serial.println("Right distance = ");

    Serial.print(distance);

    if(abs(RightDistance - LeftDistance) < 5)

    {

      moveBackward();                                  //Go to the moveBackward function

      delay(200);                                      //Pause the program for 200 milliseconds to let the robot reverse

      moveRight();                                     //Go to the moveRight function

      delay(100);                                      //Pause the program for 200 milliseconds to let the robot turn right

    }

    else if(RightDistance < LeftDistance)                  //If the distance on the right is less than that on the left then...

    {

     moveLeft();                                      //Go to the moveLeft function

     delay(100);                                      //Pause the program for half a second to let the robot turn

    }

    else if(LeftDistance < RightDistance)             //Else if the distance on the left is less than that on the right then...

    {

     moveRight();                                     //Go to the moveRight function

     delay(100);                                      //Pause the program for half a second to let the robot turn

    }

}

 

To answer your LED question

You would do it just like you wrote it. You would get a reading and then write an if statement.

if (distance < 5) {

  digitalWrite(LED, HIGH);

  } else {

  digitalWrite(LED, LOW);

}

You might even place that code in your scan function, if you have one.

Moving and making sound at the same time will be more difficult. A member has posted a way to make unique sounds. I am not sure if it is what is called non-blocking. That just means it can run without hanging up the processor doing nothing.

If I’m wrong about any of this the smart people will come along and straighten it out. :smiley:

Reply

Hi. Thank you for the confirmation.

So where in code would I add this.

As I said in my comment,

you should be able to place that code in your scan() procedure after you call the ping function. I would suggest you look at the functions available from the NewPing library that you are using. You will see it can return the distance in cm or in, if you add _ and the appropriate distance measure. You can get rid of the time variable completely.

As to coding, you should learn about global and local variables. One issue with global variables is they can be changed anywhere in the code. I know I am covering topics that are advanced to you. I want to mention that void at the beginning of a function/procedure means it will not have a return value. You can change void to any number of base variable types; such as, int, char, float, bool(ean?), byte, etc.

Enough of the coding lesson. I’m not the one to attempt teaching from my cell phone. :slight_smile:

ping

Thanks I will get to work and see what I can do. 

Like I said I am still grasping and understanding by seeing 

and trial and error

So well see.

Thanks for.your advice.

** Hi again.So I am semi**

 Hi again.

So I am semi confused. 

This is what I got out of what you suggeste

Is this what you are meaning?

 

void scan()                                         //This function determines the distance things are away from the ultrasonic sensor

{

  Serial.println("");

  Serial.println(“Scanning”);

  Time = sonar.ping(); 

  distance = Time / US_ROUNDTRIP_CM;

  delay(500);

}

void navigate()

{

    Serial.println(“There’s an obstacle!”);

if (distance < 5) {

  digitalWrite(LED, HIGH);

  } else {

  digitalWrite(LED, LOW);

}

Im slightly confused well more then slightly

Programming
You really need to learn some programming.

The actual coding is just grammar and consistency). Programming, however, is a way of thinking. It’s not difficult to pick up, but you do have to try to learn it. It’s easier if you have a good teacher, but it can be learned from books.

There are a lot of good books about programming on the Arduino.

If you have a RasPi or similar Linux box or anything that can complile C++, then Programming, Principles and Practice using C++ would be excellent. This is one of the best books I know of for learning how to think like a programmer.

Specifically for the Arduino, there is Simon Monk’s Programming Arduino: Getting Started with Sketches and Programming Arduino: Next Steps, Going Further with Sketches.

Using other people’s code does you very little good unless you understand it. It’s not difficult to learn how to think like a programmer. Many of us started with hardware and went through learning to program. I was the opposite, I was a programmer since High School (about 40 years ago) and had to learn a lot about hardware.

One of the important things to do with your code is to learn the proper coding style and that starts with indentation and capitalization and such. You should be consistent with that througout your code. There are also websited that you paste you code into and they will give you HTML that you can paste into an LMR posts and it looks right. I forget the website now, but it is highly useful. It doesn’t do the indentation and such for you, but it puts the proper tags in so that your code looks the same on LMR or other sites as it does in your editor.

If your code is correctly formatted, people are more likely to read it and help you. I’m sorry, but I looked at the mess of code with no attempt at formatting and I’m not about to jump in.

There are many reasons for not reading it, least of all is that I have a finite amount of time. If I can help somebody who has readable code it takes much less time for me to read your barely formatted code.

One of the main lessons about thinking like a programmer is that you need to remember that the computer will only do what you tell it to, not what you want it to. Therefore you need to learn how to tell the computer what to do.

Birdmum suggested putting the LED statements into the scan() function. It should be placed between the “distance = Time / …” and the “delay(500)” function. In other words, after the distance is defined and before you try to wait for anything.

Thanks

Thanks for the help. Where can I find the arduino book you mentioned

I am.definity interested in that

Tha ks again

 

To be fair

I edited my reply to tell him where the code should be placed, possibly after he saw my post. My original reply was not explicit on where my cooked up snippet should go. Even my edit wasn’t extremely explicit.

I too am working somewhat backwards to your “most people”. :slight_smile: I learned spaghetti code long before I was taught better practices. :smiley: Sadly, I didn’t even learn better practices in high school programming courses, so says my memory. Gamma rays may have come through and flipped some bits on me though. :slight_smile:

success.

Hey guys I read more and downloaded some arduino apps

I wrote the code in and changed distances abit. Ecerything smooth.

I would.like to adjust the time tge led stays lite.

Which I am.sure I can figure out.

Next on the list. A buzzer. 

Ok so bear with me.

Same concept as the led?

So say if I want the buzzer to go off when 

the when ping detects 10cm as well. would

the code and placement be the same.

Thanks again guys for your help. I

just need a extra bump in the right direction

some times… I was a welder so the ole brain

sometimes needs a kickstart in the right direction.

Buzzer will be coded the same.

However, I’m pretty sure you can’t just plug and play with the buzzer. PICAXE.com has a link to a handful of manuals. The 3rd manual covers various electronic connections. It is a free download and can be a decent reference. I wouldn’t worry about the other manuals. They cover the language which is a version of BASIC. No real sound comparison with arduino’s c/c++.

The issue with keeping the LED on longer can be covered with hardware or software. Given the choice I would probably make due with an R/C circuit (resistor/capacitor timing circuit). I’m not sure enough of my programming skills to keep the LED on longer with software.

Alrightly then

Hey guys

I just meant the code would go in the scan function

as well. Ive used the buzzer before

with melodies but never combimed

anything together.

Ive downloaded quite a few

arduino apps which seem to contain

helpful infor.

Thanks for all the help and patience.

All the book I mentioned can
All the book I mentioned can be found on Amazon. I bought the Kindle versions because I won’t be having much space shortly, plus its cheaper!

One of the best teachers I
One of the best teachers I had (in Latin) developed an entire set of Latin training programs in TUTOR, which is a horrible programming language. The entire thing was spaghetti code. My first real programming job was converting this from TUTOR into Apple II BASIC. Loosing all my code at one point (lesson: do backups) helped me immensely because when I redid it I didn’t try to copy his code, but what he meant.

thanks guys.

So I am undertanding abit more.

I wrote the code and it is working how I wanted.

I will add the delay to shorten how long its on.

Today I plan on add the buzzer.

I am going to start with a basic beep when it

senses a wall. 

I plan on maybe adding a theme

song or a melody Any ideas

of sounds to use when something 

is detected.

 

Re: code beautifier

I personally use http://hilite.me I choose C++ and colorful. I think Maxhirez posted a tip on how to place code. I believe Nilsb made a similar post including more options for code beautification. The arduino IDE includes the option to copy as HTML.