Random sound on button push with arduino and dfplayer

I've build the device that is playing the single random mp3 file from the SD card on button push, using Arduino and DFPlayer mini. The device is working almost fine. The problem is that when I push the button and do not let go instantly, the button becomes irresponsive (it stops to initiate the next random file) until I reset the Arduino. Can you please help me fix this bug?

The code:

#include "Arduino.h"
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"

const int BUTTON_PIN = 4;
int buttonState = 0;

SoftwareSerial mySoftwareSerial(3, 2); // RX, TX

DFRobotDFPlayerMini myDFPlayer;

void setup()
{
  mySoftwareSerial.begin(9600);
  Serial.begin(115200);
  pinMode(BUTTON_PIN, INPUT_PULLUP);
  
  if (!myDFPlayer.begin(mySoftwareSerial)) {  //Use softwareSerial to communicate with mp3.
    while(true){
      delay(0); // Code to compatible with ESP8266 watch dog.
    }
  }

}

void loop()
{
  byte buttonState = digitalRead(BUTTON_PIN);
  if (buttonState == LOW){
      myDFPlayer.volume(20);  //Set volume value. From 0 to 30
      myDFPlayer.play(random(1, 12));
    }
    delay(100);
  }

I moved your topic to an appropriate forum category @sonak1n.

In the future, please take some time to pick the forum category that best suits the subject of your topic. There is an "About the _____ category" topic at the top of each category that explains its purpose.

This is an important part of responsible forum usage, as explained in the "How to get the best out of this forum" guide. The guide contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

1 Like

You want to detect when the button gets pressed, not if the button is pressed. Check out the state change detection example in the IDE (File->examples->02.digital->State Change Detection) to learn how to do it.