Unable to control DFPlayer with Toggle switch; code stops

Hello Arduino Community,
I have the following code that is quite simple; I am trying to play an MP3 audio when the Toggle switch is ON and stop playing when Toggle switch is OFF.
The code works fine when the switch is OFF, as soon as I switch it on it plays the file once and then it stops. If I put it back in the OFF position and then back ON it doesn't play again. What I noticed in the logs is that when it enters the IF statement the switch is ON it plays the file and stops running the code. The issue seems in Line 35 and 36:

#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
//#define pushButtonPin 7

const int pushButtonPin = 7;

static const uint8_t PIN_MP3_TX = 2;
static const uint8_t PIN_MP3_RX = 3;

int BUTTONstate = 0; // A variable to store Button Status

SoftwareSerial softwareSerial (PIN_MP3_RX, PIN_MP3_TX);
DFRobotDFPlayerMini player;

void setup() {

Serial.begin(9600);
softwareSerial.begin(9600);
pinMode (pushButtonPin, INPUT_PULLUP);

if(player.begin(softwareSerial)) {
Serial.println("OK");
}
else {
  Serial.println("Fail");
}

}
void loop() {  // put your main code here, to run repeatedly:
int BUTTONstate = digitalRead(pushButtonPin);

if(BUTTONstate == LOW) {
  Serial.println("BUTTONstate is ON");
  Serial.println(BUTTONstate);
player.volume(30);
player.play(1);
}

if(BUTTONstate == HIGH) {
  Serial.println("BUTTONstate is OFF");
  Serial.println(BUTTONstate);
}

}

Search in the DF library documentation how player.play works.
Likely the execution continues when the playing comes to the end of the file.
Waiting for that no switches readings takes place.

I checked that function and tried adding delays to wait for the file to finish playing. The code never comes back to the loop, it seems to stop after executing the .play().

Add a debug orint after .plat: Playing done and see what comes out. Adding delays will not help.

Debugging is not supported by Arduino Nano

It sure is. Use Serial.print("Play done"); and have serial monitor started.

1 Like

I already tried printing the logs. The code never exits the IF Statement after it "plays" the file - Line 36.

By debugging I mean using Debug module :

image

Never mind I fixed it.
degitalRead of Button state will not work when executing a the play Command.

Just declared a boolean Variable and added in the IF Statement, problem solved:

if(BUTTONstate == LOW && !isPlaying) {
  Serial.println("BUTTONstate is ON");
  Serial.println(BUTTONstate);
player.volume(10);
player.play(1);

isPlaying = true;

Serial.println("File played. isPlaying is ");
Serial.println(isPlaying);
}
  
if(BUTTONstate == HIGH) {
  Serial.println("BUTTONstate is OFF");
  Serial.println(BUTTONstate);
  Serial.println("isPlaying");
  Serial.println(isPlaying);
  isPlaying = false;
}


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