#include <SPI.h>
#include <SD.h> // need to include the SD library
#define SD_ChipSelectPin 4 //using digital pin 4 on arduino nano 328, can use other pins
#include <TMRpcm.h>
#include <Servo.h>
int pos = 0; // variable to store the servo position
int count = 0; //Number of sweeps
int ledPin=8; //definition digital 8 pins as pin to control the LED
long duration; // variable for the duration of sound wave travel
int distance; // variable for the distance measurement
#define echoPin 3 // attach pin D9 Arduino to pin Echo of HC-SR04
#define trigPin 10 //attach pin D10 Arduino to pin Trig of HC-SR04
Servo servo;
TMRpcm tmrpcm; // create an object for use in this sketch
void setup()
{
Serial.begin(9600);
pinMode(ledPin,OUTPUT); //Set the digital 8 port mode, OUTPUT: Output mode
pinMode(2 , OUTPUT); //Set the digital 2 port mode, OUTPUT: Output mode
pinMode(7 , OUTPUT); //Set the digital 7 port mode, OUTPUT: Output mode
pinMode(trigPin, OUTPUT); // Sets the trigPin as an OUTPUT
pinMode(echoPin, INPUT); // Sets the echoPin as an INPUT
tmrpcm.speakerPin = 9; //5,6,11 or 46 on Mega, 9 on Uno, Nano, etc
servo.attach(5);
if (!SD.begin(SD_ChipSelectPin))
{ // see if the card is present and can be initialized:
Serial.println("SD fail");
return; // don't do anything more if not
}
else
{
Serial.println("SD ok");
}
}
void loop()
{
digitalWrite(ledPin,HIGH); //HIGH is set to about 5V PIN8
delay(1000); //Set the delay time, 1000 = 1S
digitalWrite(ledPin,LOW); //LOW is set to about 5V PIN8
delay(1000);
// Clears the trigPin condition
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin HIGH (ACTIVE) for 10 microseconds
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; // Speed of sound wave divided by 2 (go and back)
Serial.println(distance);
if(distance<20)
{
count=0;
digitalWrite(2,HIGH);
digitalWrite(7, LOW);
tmrpcm.play("ECI3.wav"); //the sound file will play each time the arduino powers up, or is reset
//audio.stopPlayback()
while (count<=5)
{
for (pos=0; pos<=180 ; pos++)
{
servo.write(pos);
delay(15);
}
for (int pos=180; pos>=0 ; pos--)
{
servo.write(pos);
delay(15);
}
count=count+1;
}
digitalWrite(2,LOW);
}
}
In my setup, once the distance sensor is activated, a sound plays , two motors start running and one servo motor starts to and fro motion. But during operation, the sound file is not playing and only there is a static noise of motor running and servo motion. Already tried USE_TIMER2 of tmrpcm library and Servotimer2 library. Please help.
Thanks in advance friends.

