DFPlayer mini mp3 automatically adjusts volume

I would like to ask everyone here why I have this program: myDFPlayer.volume(30);
Will it have no effect,I want to ask you guys what should I do to get him to move.

Because You ordered it, took it.

Please respect the advice in the topic: How to get the best out of this forum - Using Arduino / Project Guidance - Arduino Forum

Please post the entire code, according to the topic presented above.
Please translate the Chinese into English or post in a Chinese forum.


I'm sorry I didn't notice it. Please help me again. Thank you.

Sorry, it was my first time using it and I didn’t notice it

No problem. Do what You can do for us, forum helpers, and come back with more posts here.

You've posted the sketch as an image.


Apparently you believe that the sketch dwells at
myDFPlayer.play ...
till the MP3 has ended - but it does not.
It begins the play, makes the Serial.print and runs the volume back to tempVolume - all in the blink of any eye.

I'd like to ask how I can make the music play at maximum volume until it finishes playing. Thank you for your response!

Issue the volume command, issue the play command, and then monitor the BUSY pin for the track's having ended, and then adjust the volume again.

I'm sorry, I don't understand what you mean. Could you please explain it again? Thank you!

i need help on how to use busy pin in df player to arduino - Arduino Stack Exchange


Hello, I am currently using the busyPin to detect the playback of the music. This is the code I have modified. It successfully adjusts the volume to the maximum, but after about 500ms, the volume returns to its original level. I would like to ask you how to properly handle this issue.Thank you for your response!

Properly post your sketch in code tags instead of a screen capture.

Same user with duplicate topic.

#include "Arduino.h"
#include "DFRobotDFPlayerMini.h"
#include <Wire.h>
#include <VL53L1X.h>
#include <WiFi.h>

// Function prototypes
void handleButtonPress();
void handleMusicPlayback();
void sendStatusToServer(int status);

#define TCA_ADDR 0x70  // Define TCA9548A I2C multiplexer address
#define ACTIVATED LOW // Define the state when button is activated

const char* ssid = "xxxxxxxxx"; // WiFi SSID
const char* pwd = "xxxxxxxx";     // WiFi password
const char* host = "xxxxxxxx";  // Server IP
const uint16_t port = xxxxxxxx;

WiFiClient client; // Create a WiFiClient

VL53L1X sensor1;  // Initialize three VL53L1X distance sensors
VL53L1X sensor2;
VL53L1X sensor3;

DFRobotDFPlayerMini myDFPlayer; // Create a DFPlayer Mini object

int buttonPause = 5; // GPIO5 for switching songs
int buttonVolumeUp = 4; // GPIO4 for increasing volume
int buttonVolumeDown = 15; // GPIO15 for decreasing volume
int busyPin = 13; // Detect DFPlayer Mini's busy pin

int Volume = 15; // Initial volume, 30 is the maximum
int playCount = 0; // Initial play count
const int playLimit = 1; // Play limit is 1 time
bool isPlayingFirstSong = true; // Whether currently playing the first song

// Variables for tracking each song's play count
int playCountFirstSong = 0; // Track play count for the first song
int playCountSecondSong = 0; // Track play count for the second song

// Variables to store previous status of each sensor
int prevStatus1 = -1;
int prevStatus2 = -1;
int prevStatus3 = -1;
// Store previous overall status
int prevOverallStatus = -1;

// Debounce timing variables
unsigned long lastDebounceTimePause = 0;
unsigned long lastDebounceTimeVolumeUp = 0;
unsigned long lastDebounceTimeVolumeDown = 0;
unsigned long timeSensor2Status1 = 0;  // Store the time when sensor2 status is 1
const long debounceDelay = 50; // Debounce delay

// New global variables to track status and time
unsigned long sensor1ActiveTime = 0;
unsigned long sensor2ActiveTime = 0;
unsigned long sensor3ActiveTime = 0;

unsigned long previousMillis = 0;
//const long interval = 100; // Set delay time to 100 milliseconds

// Variables to store the previous button state
bool lastButtonPauseState = HIGH;
bool lastButtonVolumeUpState = HIGH;
bool lastButtonVolumeDownState = HIGH;

bool isConnected = false;

// Determine sensor status (1 or 0) based on distance value
int getDisplayValue(int distance) {
  if (distance <= 200) return 1;
  return 0;
}

// Store average distance values for three sensors
int avgDistance1[3];
int avgDistance2[3];
int avgDistance3[3];
int avgIndex = 0;  // Index counter for averages

// Network setup
void setupWiFi() {
  WiFi.mode(WIFI_STA);      // Set WiFi mode
  WiFi.begin(ssid, pwd);
  Serial.print("Connecting to WiFi");
  while (WiFi.status() != WL_CONNECTED) {
    // delay(500);
    Serial.print(".");
  }
  Serial.println("WiFi connected");
}

// Select I2C channel through TCA9548A
void tcaSelect(uint8_t i) {
  if (i > 7) return;
  Wire.beginTransmission(TCA_ADDR);
  Wire.write(1 << i);
  Wire.endTransmission();
}

// Initialize VL53L1X sensor
void initSensor(VL53L1X &sensor) {
  sensor.init(true);
  sensor.setTimeout(500);
  sensor.startContinuous(50);
}

void updateSensorStatus(int sensorStatus, unsigned long &startTime, int &confirmedStatus, unsigned long duration) {
  // Check if the current sensor status is 1
  if (sensorStatus == 1) {
    // If startTime is 0, this is the first detection of status 1
    if (startTime == 0) {
      // Record the current time
      startTime = millis();
    } else if (millis() - startTime >= duration) {
      // Check if the duration since the first detection of status 1 has exceeded the threshold
      // If so, set the confirmed status to 1
      confirmedStatus = 1;
    }
  } else {
    // If the current sensor status is not 1, reset startTime and confirmedStatus
    startTime = 0;
    confirmedStatus = 0;
  }
}

void setup() {
  Serial.begin(115200);
  Wire.begin();
  setupWiFi();
  connectToServer(); // Ensure connected to server before starting

  // Initialize distance sensors
  tcaSelect(4); // Left
  initSensor(sensor1);
  tcaSelect(3); // Center
  initSensor(sensor2);
  tcaSelect(2); // Right
  initSensor(sensor3);

  // Set button pins to input mode
  pinMode(buttonPause, INPUT_PULLUP);
  pinMode(buttonVolumeUp, INPUT_PULLUP);
  pinMode(buttonVolumeDown, INPUT_PULLUP);
  pinMode(busyPin, INPUT); // Set busyPin to input mode
  // Initialize DFPlayer Mini
  Serial2.begin(9600, SERIAL_8N1, 16, 17); // RX, TX
  if (!myDFPlayer.begin(Serial2)) {
    while (true);
  }
  myDFPlayer.volume(Volume); // Set volume
  myDFPlayer.start(); // Start playing
  myDFPlayer.playMp3Folder(1); // Initially play the first song
}

bool connectToServer() {
  int attempts = 0;
  while (!client.connected() && attempts < 10) {  // Try to connect 5 times
    Serial.println("Attempting to connect to server...");
    if (client.connect(host, port)) {
      Serial.println("Connected to server.");
      return true;
    } else {
      Serial.println("Connection failed, retrying in 1 second...");
      delay(100); // Wait 1 second before trying again
      attempts++;
    }
  }
  return client.connected();
}

void loop() {
  if (!client.connected()) {
    Serial.println("Lost connection to server, attempting to reconnect...");
    if (!connectToServer()) {
      Serial.println("Reconnection failed, will retry in next loop...");
      delay(100);
      return;  // If reconnection fails, skip the rest of this loop
    }
  }
  // Declare sensor status variables at the start of the loop
  int sensorStatus1;
  int sensorStatus2;
  int sensorStatus3;

  int status = 0;
  static unsigned long lastSensorReadTime = 0;
  const long sensorReadInterval = 10; // Read sensors every 10 milliseconds

  if (millis() - lastSensorReadTime >= sensorReadInterval) {
    lastSensorReadTime = millis();

    // Read distance from each sensor
    tcaSelect(4); // Left
    avgDistance1[avgIndex] = sensor1.read() / 10;
    tcaSelect(3); // Center
    avgDistance2[avgIndex] = sensor2.read() / 10;
    tcaSelect(2); // Right
    avgDistance3[avgIndex] = sensor3.read() / 10;

    avgIndex++;  // Update average index
  }

  // If three readings have been collected, calculate the average
  if (avgIndex == 1) {
    int avgDist1 = (avgDistance1[0]  ) / 1;
    int avgDist2 = (avgDistance2[0]  ) / 1;
    int avgDist3 = (avgDistance3[0]  ) / 1;

    // Get sensor status from distance readings
    int sensorStatus1 = getDisplayValue(avgDist1);
    int sensorStatus2 = getDisplayValue(avgDist2);
    int sensorStatus3 = getDisplayValue(avgDist3);

    // Record the time when status changes to 1
    if (sensorStatus1 == 1 && prevStatus1 == 0) {
      sensor1ActiveTime = millis();
    }
    if (sensorStatus2 == 1 && prevStatus2 == 0) {
      sensor2ActiveTime = millis();
    }
    if (sensorStatus3 == 1 && prevStatus3 == 0) {
      sensor3ActiveTime = millis();
    }

    // Confirm if status 1 has lasted for at least 1 second
    bool sensor1Confirmed = (sensorStatus1 == 1) && (millis() - sensor1ActiveTime > 1000);
    bool sensor3Confirmed = (sensorStatus3 == 1) && (millis() - sensor3ActiveTime > 1000);

    // Confirm if status 2 has lasted for at least 2 seconds
    bool sensor2Confirmed = (sensorStatus2 == 1) && (millis() - sensor2ActiveTime > 2000);

    // Update overall status based on rules
    if (sensor2Confirmed && !sensor1Confirmed && !sensor3Confirmed) {
      status = 1; // sit on bed
    } else if (sensor2Confirmed && sensor1Confirmed || sensor3Confirmed || (sensorStatus1 == 1 || sensorStatus3 == 1)) {
      status = 2; // sit by the bed or sit on bed
    } else if (!sensorStatus1 && !sensorStatus3 && (prevStatus1 == 1 || prevStatus3 == 1)) {
      status = 3; // bed exit
    } else if (sensorStatus1 == 0 && sensorStatus2 == 0 && sensorStatus3 == 0)
      status = 0; // no or on bed

    // Update previous status for each sensor
    prevStatus1 = sensorStatus1;
    prevStatus2 = sensorStatus2;
    prevStatus3 = sensorStatus3;

    // If overall status changes, output new overall status
    if (status != prevOverallStatus) {
      Serial.print("Final Status: ");
      Serial.println(status);
      prevOverallStatus = status;
    }

    // Reset average index
    avgIndex = 0;
  }
  handleButtonPress();
  handleMusicPlayback();
  sendStatusToServer(status); // Send current status to the server

  if (client.available()) {
    String response = client.readStringUntil('\n'); // Read until newline
    Serial.print("Response received from server: ");
    Serial.println(response);

    // Parse the first character as an integer
    int responseNum = response.charAt(0) - '0'; // Convert the first character to an integer
    Serial.println("Parsed response number: " + String(responseNum));

    // Play the corresponding song
    if (responseNum == 1 || responseNum == 2) {
      if (isPlayingFirstSong) {
        myDFPlayer.playMp3Folder(1); // Play the first song
        // playCountFirstSong = 0; // Reset the play count for the first song
        Serial.println("Playing the first song based on server response");
      } else {
        myDFPlayer.playMp3Folder(2); // Play the second song
        // playCountSecondSong = 0; // Reset the play count for the second song
        Serial.println("Playing the second song based on server response");
      }
    } else if (responseNum >= 3 && responseNum <= 5) { // 3: leaving bed, 4: falling down, 5: reminder of prolonged absence
      // int tempVolume = myDFPlayer.readVolume(); // Read the current volume
      myDFPlayer.volume(30); // Set the volume to maximum
      Serial.println("Volume set to maximum");
      myDFPlayer.playMp3Folder(responseNum); // Play the third or fourth song
      Serial.println("Playing song number " + String(responseNum) + " based on server response");
      while (digitalRead(busyPin) == LOW); // Wait for the busy pin to go high, indicating the song has finished playing
      // Wait for the busy pin to go low, indicating the song has finished playing
      // But do not block other operations
      handleButtonPress();
      handleMusicPlayback();
      sendStatusToServer(status);
      // Handle the response received from the server
      if (digitalRead(busyPin) == HIGH) { // If the busy pin goes high, it indicates the music has finished playing, so adjust the volume back to the original setting
        myDFPlayer.volume(Volume); // Restore the original volume after playback
        Serial.println("Playback finished, volume restored to original setting: " + String(Volume));
      }
    }
  }
}

void handleButtonPress() {
  bool currentButtonPauseState = digitalRead(buttonPause);
  bool currentButtonVolumeUpState = digitalRead(buttonVolumeUp);
  bool currentButtonVolumeDownState = digitalRead(buttonVolumeDown);

  // Pause/Switch song button
  if (currentButtonPauseState != lastButtonPauseState && (millis() - lastDebounceTimePause > debounceDelay)) {
    if (currentButtonPauseState == ACTIVATED) {
      // Switch song flag
      isPlayingFirstSong = !isPlayingFirstSong;
      if (isPlayingFirstSong) {
        myDFPlayer.playMp3Folder(1); // Play the first song
        Serial.println("Playing the first song");
      } else {
        myDFPlayer.playMp3Folder(2); // Play the second song
        Serial.println("Playing the second song");
      }
      lastDebounceTimePause = millis();
    }
  }
  lastButtonPauseState = currentButtonPauseState;

  // Volume up button
  if (currentButtonVolumeUpState != lastButtonVolumeUpState && (millis() - lastDebounceTimeVolumeUp > debounceDelay)) {
    if (currentButtonVolumeUpState == ACTIVATED && Volume < 30) {
      Volume++;
      myDFPlayer.volume(Volume);
      Serial.println("Volume increased to: " + String(Volume));
    }
    lastDebounceTimeVolumeUp = millis();
  }
  lastButtonVolumeUpState = currentButtonVolumeUpState;

  // Volume down button
  if (currentButtonVolumeDownState != lastButtonVolumeDownState && (millis() - lastDebounceTimeVolumeDown > debounceDelay)) {
    if (currentButtonVolumeDownState == ACTIVATED && Volume > 0) {
      Volume--;
      myDFPlayer.volume(Volume);
      Serial.println("Volume decreased to: " + String(Volume));  // Combine into one line
    }
    lastDebounceTimeVolumeDown = millis();
  }
  lastButtonVolumeDownState = currentButtonVolumeDownState;
}

void handleMusicPlayback() {
  if (myDFPlayer.available()) {
    int type = myDFPlayer.readType();
    if (type == DFPlayerPlayFinished) {
      int currentSongNumber = myDFPlayer.read(); // Get the current song number that has finished playing
      // Check for play finish event
      if (isPlayingFirstSong && currentSongNumber == 1) {
        playCountFirstSong++;
        if (playCountFirstSong < playLimit) {
          myDFPlayer.playMp3Folder(1); // Continue playing the first song
        }
      } else if (!isPlayingFirstSong && currentSongNumber == 2) {
        playCountSecondSong++;
        if (playCountSecondSong < playLimit) {
          myDFPlayer.playMp3Folder(2); // Continue playing the second song
        }
      }
    }
  }
}

void sendStatusToServer(int status) {
  // If the client is not connected, try to reconnect
  if (!client.connected()) {
    Serial.println("Lost connection, attempting to reconnect...");
    // Try to connect to the server
    if (client.connect(host, port)) {
      Serial.println("Successfully connected to server.");
      // Send current status after reconnecting
      String message = String(status); // Add newline character to indicate end of message
      client.print(message);
    } else {
      Serial.println("Connection failed.");
      return; // Unable to connect, exit function
    }
  } else {
    // If connection is still active and status has changed, send new status
    static int lastStatus = -1; // Last sent status
    if (status != lastStatus) {
      String message = String(status); // Add newline character to indicate end of message
      client.print(message);
      lastStatus = status; // Update last status
      delay(100);
    }
  }
}

This is my all program, When I receive 3, 4, or 5 from the server, the volume needs to be automatically set to the maximum and play the corresponding music. However, the volume is not reaching the maximum. Please advise! Thanks!

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.