Ultrasonic sensor and speaker confliction

Hi all! The system I'm trying to setup is when the distance the sensor senses become less than 4 cm, the wav file I've stored in my sd card would play from the speaker, and the green led light would turn off. But when it's between 4 and 200 cm, then the led light would stay on.

When I have two separate coding (ultrasonic sensor+led, and speaker alone) they work just fine. But when I try to combine these two (obviously I did something wrong here), the sensor is the only thing still working. The green led light wouldn't turn on no matter what the distance is, and there's no sound coming out the speaker.

Here's the code:

#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"
TMRpcm tmrpcm;

#define trigPin 13
#define echoPin 12
#define led2 10

void setup() {
tmrpcm.speakerPin = 9;
Serial.begin (9600);

pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(led2, OUTPUT);

void loop() {
long duration, distance;
digitalWrite(trigPin, LOW); // Added this line
delayMicroseconds(2); // Added this line
digitalWrite(trigPin, HIGH);
// delayMicroseconds(1000); - Removed this line
delayMicroseconds(10); // Added this line
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration/2) / 29.1;

if (distance < 4) { // This is where the LED On/Off happens


else {
if (distance >= 200 || distance <= 0){
Serial.println("Out of range");
else {
Serial.println(" cm");

Would anyone let me know the problem is? Sorry for my bad English, thank you in advance!

The problem is you have not read the how to use this forum sticky post. So your code is corrupted, or did you mean to include a smilie?