Wednesday, September 11, 2013

Fun with Ultrasonic Ranging Device and Buzzer

This is my first Arduino project. It is a subset of the object avoidance robot project that I am planning to work over the weekends. In this project, I will make Arduino scream louder as soon as anything comes closer to the range sensor (from front, obviously).

The circuit diagram is as below:
This image is created using Fritzing
Here are the components:

  1. Ultrasonic Ranging Module HC-SR04
  2. Buzzer 2 KHz
  3. 100Ω Resistor
  4. Arduino Uno
I have connected ranging modules ground to Arduino ground pin, Vcc to 5V pin, echo to pin 7, and trigger to pin 8. Buzzer's negative (black) terminal is connected to another Arduino ground pin and positive terminal is connected to a 100Ω resistor. Which, in turn, is connected to pin 5 which is a PWM pin.

Here is the Arduino sketch that I used:

const int TRIG = 8;
const int ECHO = 7;
const int BUZZ = 5;

void setup(){
  pinMode(TRIG, OUTPUT);
  pinMode(ECHO, INPUT);
  pinMode(BUZZ, OUTPUT);

void loop(){
  long duration, inches, cm;
  digitalWrite(TRIG, LOW);
  digitalWrite(TRIG, HIGH);
  digitalWrite(TRIG, LOW);
  duration = pulseIn(ECHO, HIGH);
  inches = duration / 74 / 2 ;
  cm = duration / 29 / 2 ;
  Serial.print("in, ");
  if(cm < 20){
    analogWrite(BUZZ, (20 - cm) * 10);
    digitalWrite(BUZZ, LOW);

You can see that I setup the pins in startup() and in loop I do the distance checks. I send a LOW signal for 2 microsecs, then HIGH for next 10, then turn off. I then read from ECHO input. It tells me the time in microsec that it took to get the echo of the signal that was sent. We use speed-time-distance formula to get the distance in inches and centimeters. We print it to Serial to observe this value in Serial console of Arduino IDE.

Now that we know the distance. Here comes the logic to make sound. If the object is closer than 20 cms, I write (20 - distance) * 10. This means the sound gets louder as the object comes closer to the sensor. If the object is more than 20 cms away, the buzzer will stay mum.

Here is the video. Sorry for the bad English.

Here is the final product: