Tag Archives: TRIGGER

Arduino Ultrasonic Distance Sensor

Arduino Ultrasonic Distance Sensor

Welcome to another article on a sensor which is so famous that Arduino has embedded codes to demonstrate this sensor within almost all of its very easy to use IDE versions as a default. You have probably seen this many times over with or without realizing its function.

This sensor is known as the Ultrasonic Distance Senor. As the name implies it is a sensor which is used to determine the distance of an object from the sensor. This sensor has a few version or models which are very common and widely seen. Three of them are shown below.

Ultrasonic_1
Fig a: TX and RX in one enclosure

 Ultrasonic_2Ultrasonic_3
Fig b & c: 3 pin and 4 pin version

There is many more variation of the above three. However there mode of operation are all same. Observe the following figure Ultrasonic_4Fig d: Working Principal from Parallex PING sensor datasheet

 In the above figure the famous Parallex PING Ultrasonic sensor is shown in action. It is a three pin version meaning that you control the TX and RX pulse via the same pin. Hang on what are the TX and RX pulses? You may be wondering this. Well then let’s go back to elementary physics of sound. Do you remember how the echo of a sound generated by a source could be used to measure the height of the water in a well? The same principal of echo is used by ultrasonic sensors. If you remember the range of sound people can perceive then you should know that we cannot hear above 20,000dB. Ultrasonic sounds work at much higher range meaning it is safe for us to work with.

Let’s look into a text book definition for ultrasonic sensors to get more clarity

“Ultrasonic sensors work on a principle similar to sonar which evaluates attributes of a target by interpreting the echoes from sound waves respectively. Ultrasonic sensors generate high frequency sound waves and evaluate the echo which is received back by the sensor. The time interval between the sent signal and received signal is determined to measure the distance from an object.”

The above definition simply says that you need to command the MCU (microcontroller) to send a TRIGGER or TX pulse for a defined amount of time and then LISTEN for the echo. If you remember the example of the well we calculated how long it took to hear the echo. Same is true for the ultrasonic sensor.  There is an onboard microcontroller on the ultrasonic sensor which converts the echo into time (in uS units). This time differential is then fed to the main microcontroller so that it could find out how long the echo took to come back which is a direct function of the distance. Technically the ultrasonic sensor’s MCU does the LISTENING but for ease of understanding most datasheet refers the time differential received by the main MCU as LISTENING. The onboard MCU is shown in the below figure

 Ultrasonic_5
Fig e: Onboard MCU (Middle) on PARALLEX PING SENSOR

Now let us look at some of the technical specifications of an ultrasonic sensor. I will discuss the Seeed Ultrasonic Sensor module but the specs are rarely different from other versions say example the Parallex PING sensor. The Seeed Ultrasonic sensor is shown below

Ultrasonic_6
Fig f: Seeed Ultrasonic Sensor

From the datasheet (link posted at the end of the article) the sensor is a 5V device that we connect Arduino’s 5V supply to its 5V pin. It can measure distance of an object accurately within 3cm to 4m. However if the body gets too close to the sensor, it fails to catch the echo and measure the time differential.

 Other key specs are, it needs 15mA of current, has a resolution of 1cm etc. But when looking for Ultrasonic sensor, pay special attention to the TRIGGER PULSE WIDTH and angle of sight i.e the area of line of sight of the sensor. This point is best explained by their practical performance chart given below Ultrasonic_7Fig g: Practical Performance Chart

Observe the chart, the sensor works best between 30 degree i.e when an object will be within this zone the Ultrasonic sensor will be able to accurately judge the distance of the object. Beyond this area the sensor will fail. This is very crucial if you plan on building collision avoidance robot or something similar.

If you go to the examples in the Arduino you can find the Ping sensor demo under the Sensor category. Just connect and experience the senor’s magic first hand. But I found this to be a little boring. Hence I came up with a bit trickier but more detailed version of the experiment. Just follow the instructions in the source code and hook up the circuit as described in the comment section. If done correctly you should be able to see the following results. What the leds does is show visually the range of object from the ultrasonic sensor.

 Ultrasonic_8
Fig: Full Circuit with No Obstacle

 Ultrasonic_9
Fig: With Obstacle at very close range

 Ultrasonic_10
Fig: Output at Serial Monitor with no objects

Ultrasonic_11
Fig: Output when object is very close to the sensor

I hope you enjoyed the article and the experiment. If you want to do the experiment in UNO board or any other board then you need to just change the following section after copy pasting the code into a new sketch in Arduino Ultrasonic_12Fig: Pin definitions

You can add even a lot more leds to give better visual representation just by manipulating the code a bit. If you do this experiment you may see an error but I will leave it up to you guys to solve it. Remember to use resistors with LEDS and NEVER connect them directly with Arduino. I used five 330ohm resistances.

Check out the following links if you want to get more data

1)    http://www.seeedstudio.com/depot/datasheet/Seeed%20Ultrasonic%20Sensor%20datasheet.pdf

2)    http://www.radioshack.com/graphics/uc/rsk/Support/ProductManuals/2760031_PM_EN.pdf

DOWNLOAD SOURCE CODE TO PROJECT BELOW OR COPY THE CODE BELOW
SOURCE CODE


                                                                //ULTRASONIC SENSOR IMPLEMENTATION WITH LEDS----VERSION 1.0//
                                                                // DATE 5TH DECEMBER 2013
                                                                // LICENSE: OPEN SOURCE/FREE

/*
-- A SIMPLE PROJECT BASED USING 5 LEDS, 1 PING ULTRASONIC SENSOR AND ARDUINO MEGA
-- DO NOT DIRECTLY CONNECT LEDS WITH ARDUINO!! USE A RESISTOR WITH EACH OF THE LEDS TO LIMIT THE CURRENT FLOW OTHERWISE BOTH THE LEDS AND THE BOARD MAY BE PERMANENTLY DAMAGED
-- THE LEDS ARE PROGRAMMED TO GIVE AN VISUAL CONFORMATION OF THE DISTANCE BETWEEN THE SENSOR AND THE OBJECT
-- IT IS PROGRAMMED TO SHOW LEVEL BETWEEN 3 - 150 CM.
-- DIGITAL PINS 21 TO 26 ARE SELECTED FOR DRIVING THE LEDS AND EACH OF THEM IS COUPLED WITH A 330ohm RESISTOR.
-- USB POWER SOURCE IS USED
-- THE SENSOR USED IN THIS EXPERIMENT ARE THOSE WHICH HAS 3 PINS VIZ:- GND, +5V AND SIGNAL.
-- PWM PIN 7 IS SELECTED AS THE BI-DIRECTIONAL PIN REQUIRED TO CONTROL AND READ DATA FROM THE ULTRASONIC SENSOR
-- THE SENSOR HAS A ERROR OF +-2% IN COMPARISON TO THE READINGS FROM THE BUILT IN EXAMPLE OF ARDUINO IDE AND WITH A LINEAR SCALE READING
-- 
-- EACH OF THE LED WILL CONSUME ABOUT 10-15mA OF CURRENT.
-- A USB JACK OF A COMPUTER CAN ROUGHLY SUPPLY ABOUT 500mA TOPS WHICH IS MORE THAN ENOUGH FOR THIS PROJECT
-- THE DISTANCE OF THE OBJECT WILL ALSO BE SHOWN IN THE SERIAL MONITOR
-- RED LED WILL LIGHT UP WHEN IT COMES IN A CERTAIN DISTANCE TO THE SENSOR
-- THIS SENSOR REQUIRES 5V SUPPLY.
-- FOR MORE INFORMATIONS ON THE BUILT IN FUNCTIONS AND LIBRARIES THAT ARE USED PLEASE REFER TO arduino.cc/reference 

-- A NOTE: WHEN DEFINING VARIABLES ASSOCIATED WITH PIN NUMBER YOU CAN USE INT BUT I PREFER CHAR AS IT TAKES LESS MEMORY SPACE CUZ IT IS 8BIT WHEREAS INT IS 16BIT.
-- THE TIME PERIOD FOR THE TRANSMITTED PULSE IS 10uS AND IT STARTS WITH HALF CYCLE LOW AND THE REST HALF CYCLE AS HIGH
-- THE CODE IS NOT THE MOST EFFICIENT BUT I WROTE IT INTENTIONALLY TO JUST GIVE AN EASY FRAMEWORK ON USING ULTRASONIC SENSORS AND TO SHOW HOW THE DATA CAN BE VERY EASILY MANIPULATED
-- AN ERROR WILL BE OBSERVD AND IT IS THE SENSOR CANNOT ACCURATELY DETECT RAPID RELATIVE MOTION BETWEEN THE OBJECT AND ITSELF FOR THAT REASON THE LAST RED LED LIGHTS UP CUZ THE OUTPUT VALUE IS SHOWN TO BE 1
*/

//---------------------------------------PIN DEFINITIONS---------------------------//
const char signalPIN=2; // Signal PIN of the paralex knockoff PING sensor is connected to the digital pin 2
const char ledPIN_5=26; // GREEN LED 1
const char ledPIN_4=25; // YELLOW LED 2
const char ledPIN_3=24; // YELLOW LED 1
const char ledPIN_2=23; // RED LED 2
const char ledPIN_1=22; // RED LED 1
//---------------------------------------------------------------------------------//



//--------------------------------------------GLOBAL VARIABLES-----------------------//
int distance; // An interger variable that will contain the distance measured from the returning pulse.
unsigned long pulseduration=0; // A long varible that will contain the number of milisecond of the returning pulse.
unsigned int i = 0; 



//---------------------------------------------FUNCTION PROTOTYPE---------------------//
void measureDistance();  // This function will convert the recevied pulse duration into cm.
void Ledcheck();         // A simple function which will allow you to see whether the connection to any led is missing or any led is fused or not. 

void Led_shutoff();




void setup()
{


pinMode(ledPIN_5, OUTPUT);
pinMode(ledPIN_4, OUTPUT);
pinMode(ledPIN_3, OUTPUT);
pinMode(ledPIN_2, OUTPUT);
pinMode(ledPIN_1, OUTPUT);

//CONFIGURING PINS CONNECTED WITH LEDS AS OUTPUT SO THAT WHEN THE CORRESPONDING PIN WILL BE HIGH THE CIRCUIT WILL BE COMPLETE AND THAT LED WILL LIGHT UP

Serial.begin(9600); // Initializing serial monitor.

Ledcheck(); // IN SETUP LOOP STATEMENTS WILL RUN ONLY ONCE AND THUS THE LEDCHK FUNCTION IS CALLED SINCE IT IS NEEDED TO BE RUN ONLY ONCE

}


void loop()
{

measureDistance(); // Function call to get the pulseduration
pulseduration=pulseduration/2; // The principle of sound and echo time to reach the object = total time / 2
distance = int(pulseduration/29); // THE LONG VALUE WILL BE AUTOMATICALLY CONVERTED INTO INTEGER

if ( distance >= 15)
  {
    Led_shutoff();
    digitalWrite (ledPIN_5, HIGH); 
    delay(500); // 1 second delay to make the led visible
  
  
  }
    else if (distance =12)
        {
            Led_shutoff();
            digitalWrite (ledPIN_4, HIGH); 
            delay(500); // 1 second delay to make the led visible
            
        }
          else if (distance =9)
            {
                Led_shutoff();
                digitalWrite (ledPIN_3, HIGH); 
                delay(500); // 1 second delay to make the led visible
            
            
            }
              else if (distance =4)
                {
                
                    Led_shutoff();
                    digitalWrite (ledPIN_2, HIGH); 
                    delay(500); // 1 second delay to make the led visible
                
                }
                else // Since the above conditions wasn't satisfied it means either the sensor is disabled or the object is too close to the sensor.
                  {
                        Led_shutoff();                
                        digitalWrite (ledPIN_1, HIGH); 
                        delay(500); // 1 second delay to make the led visible
                  
                  }



// Display on serial monitor

Serial.println("Distance-  ");
Serial.println(distance);
Serial.println(" cm");
delay(500);
}




//--------------------------------------------------FUNCTION BODY---------------------------------//
void measureDistance() 
{
  // set pin as output so we can send a pulse
  pinMode(signalPIN, OUTPUT); // Do not mistake this line as a code redundancy this is needed to reset the pin as output for next run
  // set output to LOW
  digitalWrite(signalPIN, LOW);
  delayMicroseconds(5);
 
  // now send the 5uS pulse out to activate Ping)))
  digitalWrite(signalPIN, HIGH);
  delayMicroseconds(5);
  digitalWrite(signalPIN, LOW);
 
  pinMode(signalPIN, INPUT); // Since the digital pins are BI-DIRECTIONAL their input/output characters can be switeced at any time using the software. Switched to input
  // THE TRIGGER PULSE AND THE ECHO ARE HANDELED BY 1 PIN IN THIS KIND OF ULTRA-SONIC SENSOR
 
  // finally, measure the length of the incoming pulse
  pulseduration=pulseIn(signalPIN, HIGH); // the length of pulse in microseconds.
}

void Ledcheck()
{
      digitalWrite(ledPIN_5,HIGH); // POWERING THE LED
      delay(1000); // Holding it for a second
      digitalWrite(ledPIN_5,LOW); // POWERING DOWN
 
      digitalWrite(ledPIN_4,HIGH); // POWERING THE LED
      delay(1000); // Holding it for a second
      digitalWrite(ledPIN_4,LOW); // POWERING DOWN 
  
      digitalWrite(ledPIN_3,HIGH); // POWERING THE LED
      delay(1000); // Holding it for a second
      digitalWrite(ledPIN_3,LOW); // POWERING DOWN 
   
   
      digitalWrite(ledPIN_2,HIGH); // POWERING THE LED
      delay(1000); // Holding it for a second
      digitalWrite(ledPIN_2,LOW); // POWERING DOWN 
    
      digitalWrite(ledPIN_1,HIGH); // POWERING THE LED
      delay(1000); // Holding it for a second
      digitalWrite(ledPIN_1,LOW); // POWERING DOWN  
    

  Serial.println("LED checking complete.");
  Serial.println(" ");
  Serial.println(" ");
  return ; 

}

void Led_shutoff()
{

  digitalWrite (ledPIN_5, LOW);
  digitalWrite (ledPIN_4, LOW);
  digitalWrite (ledPIN_3, LOW);
  digitalWrite (ledPIN_2, LOW);
  digitalWrite (ledPIN_1, LOW);
  //delay(100); // THIS DELAY WILL CAUSE BLINKING IN THE LEDS
}