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().