I made a project that the mp3 player will play after the ultrasonic sensor detects any object at 5 cm. The ultrasonic sensor works properly but the mp3 module does not work. I use a “Voice Playback Module Board MP3 Music Player 5W MP3 DY-SV5W“ and connect with a speaker. I am not sure if there is a problem with my code or the hardware module or my wiring. I have tried to connect the mp3 module separately to make sure that it is working properly or not but still, it didn't work. I named the wav file in the SD card as “1.wav”
This is my code:
#include "DYPlayerArduino.h"
#include <Wire.h>
DY::Player player;
const int trig = 6; // Ultrasonic trigger pin
const int echo = 7; // Ultrasonic echo pin
const int led = 13; // LED pin
long duration, distance;
int vol = 15;
bool isPlaying = false;
void setup() {
Serial.begin(9600);
pinMode(echo, INPUT);
pinMode(trig, OUTPUT);
pinMode(led, OUTPUT);
player.begin();
player.setVolume(vol);
player.setCycleMode(DY::PlayMode::OneOff); // Play the file once
}
void loop() {
// Trigger ultrasonic sensor
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
// Read distance
duration = pulseIn(echo, HIGH);
distance = (duration / 2) / 29.1;
Serial.print(distance);
Serial.println(" cm");
if (distance <= 5 && !isPlaying) { // Play music if distance <= 5 cm
digitalWrite(led, HIGH);
player.play();
isPlaying = true;
} else if (distance > 5 && isPlaying) { // Stop music if distance > 5 cm
digitalWrite(led, LOW);
player.stop();
isPlaying = false;
}
delay(300);
}
This is my wiring: