Ultrasonic trigger sd card module

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!

Welcome to the forum

Please follow the advice given in the link below when posting code, in particular the section entitled 'Posting code and common code problems'

Use code tags (the < CODE/ > icon above the compose window) to make it easier to read and copy for examination

https://forum.arduino.cc/t/how-to-get-the-best-out-of-this-forum

In my experience the easiest way to tidy up the code and add the code tags is as follows
Start by tidying up your code by using Tools/Auto Format in the IDE to make it easier to read. Then use Edit/Copy for Forum and paste what was copied in a new reply. Code tags will have been added to the code to make it easy to read in the forum thus making it easier to provide help.

It depends on the schematics.

do you know something similar that i can use? thank you!

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