Sparkfun Mp3 Shield + Ping)) + Arduino

Hi,

I'm very new to Arduino and programming. I am attempting to make a mp3 play(sparkfun mp3 shield), when triggered by an ultrasonics Sensor (parallax Ping). I understand that this is a common project, however I'm struggling to figure it out - Have been putting disparate code together, and have so far got here. It compiles, but doesn't work. Please, any help is greatly appreciated. Thanks

#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h> 
#include <SFEMP3Shield.h>

SdFat sd;
SFEMP3Shield MP3player;

const int pingPin = 7;

void setup() {

  Serial.begin(9600);
  sd.begin(SD_SEL, SPI_HALF_SPEED);
  MP3player.begin();
}

void loop()
{

  long duration, cm;
  
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);
  
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  cm = microsecondsToCentimeters(duration);
  
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
  
  
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;

//if distance is breached play track
  if (microseconds < 10)

  //start playing track 1
  MP3player.playTrack(1);

delay(2000);
}
long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;

  //if distance is breached play track
  if (microseconds < 10)

    //start playing track 1
    MP3player.playTrack(1);

  delay(2000);
}

This function will return the value of microseconds / 29 / 2 before you test the value of microseconds. Prove it by printing the value of microseconds before you test it.

Thanks very much for your reply. Yes, the serial monitor does print the distance in CM, but no sound sadly

Yes, the serial monitor does print the distance in CM, but no sound sadly

That's because you are printing it in the loop() function after the value has been returned by the function. Try printing it in the function just before you do the test. Print a text label as well so that you know where the print is coming from.