Still too much code.
(Uncompiled, untested)
#include <Arduino.h>
#include <SoftwareSerial.h>
#include <DFRobotDFPlayerMini.h>
SoftwareSerial mySoftwareSerial(10, 11); // RX, TX
DFRobotDFPlayerMini myDFPlayer;
struct Sensor {
const byte triggerPin;
const byte echoPin;
const byte playFile;
const char* direction;
} sensors [] = { {7, 6, 2, "Left" },
{2, 3, 3, "Right"},
{4, 5, 1, "Centre"}};
void setup()
{
for (auto& sensor : sensors) {
pinMode(sensor.triggerPin, OUTPUT);
digitalWrite (sensor.triggerPin, LOW);
pinMode (sensor.echoPin, INPUT);
}
Serial.begin(115200);
mySoftwareSerial.begin(9600);
Serial.begin(115200);
Serial.println();
Serial.println(F("DFRobot DFPlayer Mini Demo"));
Serial.println(F("Initializing DFPlayer ... (May take 3~5 seconds)"));
if (!myDFPlayer.begin(mySoftwareSerial)) { //Use softwareSerial to communicate with mp3.
Serial.println(F("Unable to begin:"));
Serial.println(F("1.Please recheck the connection!"));
Serial.println(F("2.Please insert the SD card!"));
while (true) {
delay(0); // Code to compatible with ESP8266 watch dog.
}
}
Serial.println(F("DFPlayer Mini online."));
myDFPlayer.volume(10);
//myDFPlayer.setLoopMode(myDFPlayer_LOOP_NONE);
}
void loop()
{
for (auto& sensor : sensors) {
delay(500);
Serial.println("\n");
digitalWrite (sensor.triggerPin, HIGH);
delayMicroseconds (10);
digitalWrite (sensor.triggerPin, LOW);
uint32_t duration = pulseIn (sensor.echoPin, HIGH);
uint32_t distance = (duration / 2) / 29.1;
if (distance < 30) {
Serial.print(sensor.direction);
Serial.print(F(" Distance "));
Serial.print(distance);
myDFPlayer.play(sensor.playFile);
}
}
}