Hello Forum,
I'm trying to get an ultra sonic sensor to trigger 3 dfplayers. The problem is that once the ultrasonic sensor has been triggered the dfplayers starts to play in a loop.
I just need the track to be played once until the sensor is being triggered again.
Could someone perhaps see if I need to change something in the code?
Your help would be much appreciated.
Thank you.
#include "SoftwareSerial.h"
#include "DFRobotDFPlayerMini.h"
// defines pins numbers
const int trigPin = 9;
const int echoPin = 13;
// defines variables
long duration;
int distance;
// Use pins 11 and 10 to communicate with DFPlayer Mini
static const uint8_t PIN_MP3_TX = 11; // Connects to module's RX
static const uint8_t PIN_MP3_RX = 10; // Connects to module's TX
SoftwareSerial softwareSerial(PIN_MP3_RX, PIN_MP3_TX);
// Create the Player object
DFRobotDFPlayerMini player;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Init USB serial port for debugging
Serial.begin(9600);
// Init serial port for DFPlayer Mini
softwareSerial.begin(9600);
// Start communication with DFPlayer Mini
if (player.begin(softwareSerial)) {
Serial.println("OK");
// Set volume to maximum (0 to 30).
player.volume(30);
// Play the first MP3 file on the SD card
//player.play(1);
} else {
Serial.println("Connecting to DFPlayer Mini failed!");
}
// player.volume(30); //(30 max, 15 min)
// Play the first MP3 file on the SD card
//player.play(1);
// player.loop(1);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance);
//change distances here
if (distance > 1 && distance <= 8) { //distance in centimeter, fx between 1 - 8 cm
for(int i = 0; i < 50; i++){
player.play(1);
delay(10000);
player.stop();
}
Serial.println("track 1 playing");
//distance = get_ultrasonic_distance();
delay(5000); //delay in milli seconds - controls how long the relay is on for
}
else {
//player.play(1);
Serial.println("off");
//distance = get_ultrasonic_distance();
player.stop();
}
}
long get_ultrasonic_distance()
{
long distance_ = 0;
distance_ = duration*0.034/2;
if ((distance_ != 0))
{
return distance_;
}
else return 0;
}