Autres Cours

Arduino Distance Measurement with Audio | Ultrasonic Sensor + DFPlayer Mini

Circuit Diagram

In this tutorial, we will explore how to use an ultrasonic sensor to measure distance and trigger audio feedback using the DFPlayer Mini module. This project integrates the HC-SR04 ultrasonic sensor, which can measure distances between 2 cm and 400 cm, and the DFPlayer Mini, an MP3 audio player module that plays pre-recorded sounds based on the measured distance. The system will provide audible notifications depending on the proximity of objects, making it a fun and practical project for beginners and intermediate Arduino users.

Components Used

Arduino Uno

Arduino Uno

HC-SR04 Ultrasonic Sensor

Ultrasonic Sensor

DFPlayer Mini

DFPlayer Mini

1KOhm Resistor

Resistor

20 Ohm 1 Watt Speaker

Speaker

SD Card (formatted FAT16 or FAT32)

SD Card

Ultrasonic Sensor (HC-SR04) Overview

The HC-SR04 is one of the most popular ultrasonic sensors used in distance measurement projects. This sensor emits ultrasonic waves and calculates the time it takes for the waves to return after hitting an object, determining the distance.

Pinout

  • VCC – 5V power supply
  • TRIG – Trigger pin sends out ultrasonic pulses
  • ECHO – Echo pin listens for the reflected signal
  • GND – Ground

Specifications:

  • Power Supply: 5V DC
  • Current Consumption: 15mA
  • Operating Frequency: 40Hz
  • Measurement Range: 2cm to 400cm
  • Resolution: 0.3 cm
  • Measurement Angle: 15 degrees
  • Trigger Pulse Width: 10µs

DFPlayer Mini Overview

The DFPlayer Mini is a small MP3 player module capable of playing MP3, WAV, and WMA files. It is often used for projects requiring simple audio output. The module includes an SD card adapter that supports up to 32GB of FAT16/FAT32 cards, making it easy to store and play audio files.

Key Features:

  • Supports formats like MP3 WAV and WMA
  • Includes an SD card slot for up to 32GB (FAT16/FAT32)
  • Simplified output directly connected to a speaker
  • Powered by 3.2V or 5V DC
  • Communicates with the microcontroller using the UART protocol

Wiring

Ultrasonic Sensor to Arduino:

Ultrasonic Wiring

DFPlayer Mini to Arduino and Speaker:

DFPlayer Wiring

Note: Place a 1KOhm resistor between DFPlayer Mini's RX pin and Arduino's Pin 3.

Circuit Diagram

Full Circuit

Code Breakdown

Let's break down the code step by step.

#include <VARSTEP_ultrasonic.h>   // Custom library for controlling the ultrasonic sensor
#include "SoftwareSerial.h"       // SoftwareSerial library for communication with the DFPlayer
#include "DFRobotDFPlayerMini.h"  // DFPlayer Mini control library

VARSTEP_ultrasonic.h: This is a custom library to handle ultrasonic sensor operations, like measuring distance.

SoftwareSerial.h: This library allows the Arduino to create additional software-based serial communication ports, in this case, for the DFPlayer Mini.

DFRobotDFPlayerMini.h: This library is specifically designed to control the DFPlayer Mini module for playing audio files.

#define trigger_pin 8             // Pin connected to the TRIG pin of the ultrasonic sensor
#define echo_pin 9                // Pin connected to the ECHO pin of the ultrasonic sensor

trigger_pin and echo_pin: These define the Arduino pins that are connected to the ultrasonic sensor's TRIG and ECHO pins, respectively. The trigger pin sends the pulse, and the echo pin receives the reflected signal.

double distance_cm, distance_m;   // Variables to store the distance in centimeters and meters

distance_cm and distance_m: These are variables that store the measured distance in centimeters (distance_cm) and meters (distance_m), which will be calculated from the ultrasonic sensor.

Setup Function

void setup() {
  mySoftwareSerial.begin(9600);        // Start DFPlayer communication at 9600 baud
  Serial.begin(115200);                // Begin serial communication at 115200 baud

  while (!Serial);  // Wait for serial communication to start

  if (!myDFPlayer.begin(mySoftwareSerial)) {  // Initialize DFPlayer Mini
    Serial.println("Not initialized: Check connections and SD card."); 
    while (true);  // Halt if initialization fails
  }

  Serial.println("DFPlayer Mini initialized!");  
  myDFPlayer.setTimeOut(500);  // Set serial communication timeout to 500ms
  myDFPlayer.volume(30);       // Set volume to 30
  myDFPlayer.EQ(0);            // Set equalizer to normal
}

Initialization: The setup function configures serial communication, initializes the DFPlayer Mini, and sets up basic parameters like volume and equalizer settings.

Loop Function

void loop() {
  unsigned long currentMillis = millis();  // Get the current time

  if (currentMillis - loopDelayMillis >= loopDelayInterval) {
    loopDelayMillis = currentMillis;  // Update loop delay

    distance_cm = my_HCSR04.distance_cm();  // Measure distance in centimeters
    distance_m = my_HCSR04.distance_m();    // Measure distance in meters

    if (distance_cm == -1.0) {
      Serial.println("No distance detected");
      trackPlayed = false;  // Reset track flag
    } else {
      if (!trackPlayed || currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;  // Update time

        // Play specific audio based on the measured distance
        if (distance_cm <= 3.99 && distance_cm >= 3.80) {
          myDFPlayer.play(1);  // Play audio track 1
        } else if (distance_cm <= 5.99 && distance_cm >= 4.99) {
          myDFPlayer.play(2);  // Play audio track 2
        } else if (distance_cm <= 7.99 && distance_cm >= 6.99) {
          myDFPlayer.play(3);  // Play audio track 3
        } else if (distance_cm <= 9.9 && distance_cm >= 8.99) {
          myDFPlayer.play(4);  // Play audio track 4
        }

        trackPlayed = true;  // Mark track as played
      }
    }

    // Output distance to the Serial Monitor
    Serial.print("Distance: ");
    Serial.print(distance_cm);
    Serial.print(" cm | ");
    Serial.print(distance_m);
    Serial.println(" m");
  }
}

Main Logic: The loop function continuously measures distance and plays appropriate audio tracks based on the measured distance ranges, with timing controls to prevent audio overlap.

Complete Code

#include <VARSTEP_ultrasonic.h>
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

#define trigger_pin 8
#define echo_pin 9

double distance_cm, distance_m;

VARSTEP_ultrasonic my_HCSR04(trigger_pin, echo_pin);

SoftwareSerial mySoftwareSerial(2, 3);
DFRobotDFPlayerMini myDFPlayer;

unsigned long previousMillis = 0;
unsigned long loopDelayMillis = 0;
const long interval = 2000;
const long loopDelayInterval = 100;
bool trackPlayed = false;

void setup() {
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);

  while (!Serial);

  if (!myDFPlayer.begin(mySoftwareSerial)) {
    Serial.println("Not initialized: Check connections and SD card."); 
    while (true);
  }

  Serial.println("DFPlayer Mini initialized!");  
  myDFPlayer.setTimeOut(500);
  myDFPlayer.volume(30);
  myDFPlayer.EQ(0);
}

void loop() {
  unsigned long currentMillis = millis();

  if (currentMillis - loopDelayMillis >= loopDelayInterval) {
    loopDelayMillis = currentMillis;

    distance_cm = my_HCSR04.distance_cm();
    distance_m = my_HCSR04.distance_m();

    if (distance_cm == -1.0) {
      Serial.println("No distance detected");
      trackPlayed = false;
    } else {
      if (!trackPlayed || currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;

        if (distance_cm <= 3.99 && distance_cm >= 3.80) {
          myDFPlayer.play(1);
        } else if (distance_cm <= 5.99 && distance_cm >= 4.99) {
          myDFPlayer.play(2);
        } else if (distance_cm <= 7.99 && distance_cm >= 6.99) {
          myDFPlayer.play(3);
        } else if (distance_cm <= 9.9 && distance_cm >= 8.99) {
          myDFPlayer.play(4);
        }

        trackPlayed = true;
      }
    }

    Serial.print("Distance: ");
    Serial.print(distance_cm);
    Serial.print(" cm | ");
    Serial.print(distance_m);
    Serial.println(" m");
  }
}

How the Project Works

The HC-SR04 ultrasonic sensor measures the distance to an object.

The DFPlayer Mini plays different pre-recorded audio files from the SD card depending on the measured distance. The system checks the distance in real time and only plays an audio file if a specific range is detected. Once a track is played, it waits for 2 seconds before checking the distance again and playing another track if necessary.

Produits Recommandés

No products are available