Hello guys! i want to make a project but somethink wrong happend! I have an sd card module with one track on it! I want to start playing music when ultrasonic sencor trigged! To stop when the track finish and star again when something trigg again the ultrasonic sencor! Is this code right?
#include <SD.h>
#include <TMRpcm.h>
#include <SPI.h>
#define SD_ChipSelectPin 4 // SD card select pin
#define trigPin 2
#define echoPin 3
#define speakerPin 9
TMRpcm tmrpcm;
bool isPlaying = false; // Flag to keep track of the music state
void setup() {
Serial.begin(9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("SD initialization failed!");
return;
}
tmrpcm.speakerPin = speakerPin;
tmrpcm.setVolume(6); // Adjust volume (0-7)
Serial.println("Setup complete.");
}
void loop() {
long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) / 29.1;
if (distance < 10) { // Distance threshold for starting music
if (!isPlaying) {
tmrpcm.play("music.wav"); // Ensure the file is named correctly and placed in the root directory of the SD card
isPlaying = true;
Serial.println("Music started");
}
} else {
if (isPlaying) {
tmrpcm.stopPlayback(); // Stop the music
isPlaying = false;
Serial.println("Music stopped");
}
}
delay(200); // Short delay to prevent excessive triggering
}
Thank you very much!