ultrasonic sensor

could some one plz explain and or attach a program on how to use/program an ultrasonic sensor. i need to know how to use it to tell me how far i am from an obstical and react when something is too close.

sorry for all of the questions, but i am new to programing (never had a class) and i am only in high school, so plz forgive me.


If you have it hooked up right you can use it in your code like this. This how you would make it drive to within X distance of an object. Put in a get sonicSensor command. Make a while loop after that while sonicSensor < X]. Define sonicSensor as a variable. Put in that loop the forward motor commands for that bot. And another get sonicSensor. This makes it check the distance to the object everytime it goes through the loop and causes the while statement to become false when you are the given distance from the object. After the loop put the motor stop commands.
hope this helps

I don’t know what programming software you are using, but EasyC has some sample and test programs that might help. From them you can get an idea of how to write the program and then just add the motor controls.

Very simply:

  1. You could remove the print statements from the test program.
  2. Add an “IF” and “Else” statement after getting the reading from the sensor.
    “IF” reading from sensor < some number then stop motors.
    “Else” set motors to make robot go forward.

All of this would go inside of the “While” loop so that you continously get readings from the sensor and check them with the “IF” statement.

Plus, EasyC has a great help section.

The Scaredybot project in this document demonstrates the use of the ultrasonic sensor. It has step-by-step building and programming instructions.

I would be much easier to put everything in a while loop,
-With your first command get a ultra block and tell your sensor to start
-the second command should be to retreive and send info to a variable
-for the while loop do somethin like this:
while { ultra < 100 && ultra >10 ;
{getulta 1,11} >constantly get new info from the sensor
[Motor commands for forward]
[motor commands for stop]
^^^^^^this program should have you robot go forward utill it is about 6 inches from a wall Add an if statement to have the robot go backwards if the number is to small ie. too close to an obstacle

The easyC help file also has information and an example program.