How to make sound alert with ultrasonic sensor

In this post you will know  how  to build a sound alarm with ultrasonic sensor. You can use this system in many places. For example: Sound guide, (to guide someone to certain direction when he/she comes front of the sensor) to make yourself aware of something or someone and many more.



The sketch

#include <SoftwareSerial.h>
#define ARDUINO_RX 5 //should connect to TX of the Serial MP3 Player module
#define ARDUINO_TX 6 //connect to RX of the module
SoftwareSerial mySerial(ARDUINO_RX, ARDUINO_TX);
static int8_t Send_buf[8] = {0} ;

#define CMD_SEL_DEV 0X09
#define DEV_TF 0X02
#define CMD_PLAY_W_VOL 0X22

int trigPin1 = 9;
int echoPin1 = 8;

void setup()
{
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
      mySerial.begin(9600);
        Serial.begin(9600);
      delay(500);//Wait chip initialization is complete
        sendCommand(CMD_SEL_DEV, DEV_TF);//select the TF card 
      delay(200);//wait for 200ms
}

void loop() {
delay(280);
Serial.println("\n");
 int duration1, distance1;
  digitalWrite (trigPin1, HIGH);
  delayMicroseconds (10);
  digitalWrite (trigPin1, LOW);
  duration1 = pulseIn (echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

      Serial.print("1st Sensor: ");
      Serial.print(distance1);
      Serial.print("cm  ");

  if (distance1 < 40) {  // Change the number for long or short distances.
 sendCommand(CMD_PLAY_W_VOL, 0X1E001);//play the second song with volume 30 class
   delay(300);
  } else {
// nothing
  }  
}

void sendCommand(int8_t command, int16_t dat)
{
  delay(20);
  Send_buf[0] = 0x7e; //starting byte
  Send_buf[1] = 0xff; //version
  Send_buf[2] = 0x06; //the number of bytes of the command without starting byte and ending byte
  Send_buf[3] = command; //
  Send_buf[4] = 0x00;//0x00 = no feedback, 0x01 = feedback
  Send_buf[5] = (int8_t)(dat >> 8);//datah
  Send_buf[6] = (int8_t)(dat); //datal
  Send_buf[7] = 0xef; //ending byte
  for(uint8_t i=0; i<8; i++)//
  {
    mySerial.write(Send_buf[i]) ;
  }

}

What do you need:
1x Arduino board
1x Ultrasonic Sensor
1x Serial MP3 player
1x Loud speaker
1x SD card with a sound track in (Make sure you name the sound track 001)
And Few jumper wires.

Note: If you need extra help to set the sound please see this post.

Watch the video to see the sketch in action

3 comments:


  1. shared coding for two ultrasonic sensors

    ReplyDelete
    Replies
    1. shared coding for two ultrasonic sensors.. help me

      Delete
  2. This comment has been removed by a blog administrator.

    ReplyDelete



Newly posted:
Reason why rich getting richer and poor getting poorer