0

I have a project where if you change the value of the spdt switch the colour of the LEDs change. As well as this a .wav file plays. The problem is I only want the .wav to play once. At the moment it constantly plays over and over as it's within the loop. I've tried using a mute or disabling the pin after the play through but I am unable to re-enable so I scrapped it. I deally I want to keep the SPDT switch due to asthetics instead of a push switch. This is my code:

#include <TMRpcm.h>
#include <SD.h>                       
#define SD_ChipSelectPin 10             
#include <SPI.h>

TMRpcm tmrpcm;

void setup() 
{
// put your setup code here, to run once:

tmrpcm.speakerPin=9;                          
Serial.begin(9600);
if(!SD.begin(SD_ChipSelectPin))
{
  Serial.println("SD fail");
  return;
}
     tmrpcm.setVolume(6);
     tmrpcm.play("1.wav");
     while (tmrpcm.isPlaying()) {
     delay(1);
}
     tmrpcm.setVolume(6);
     tmrpcm.play("3.wav");
//set the switch input, pin 8, as an 
pinMode(8, INPUT);

//set both the LED pins, pin 5 and 6 as OUTPUTs 
pinMode (5, OUTPUT); 
pinMode (6, OUTPUT); 
 delay(1000);
}

void loop() 
{
 int switchValue = digitalRead(8);
 if (switchValue == 1)
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
  tmrpcm.setVolume(6);
  tmrpcm.play("4.wav");
  digitalWrite(5,HIGH);
  digitalWrite(6,LOW);

}
else
{
   while (tmrpcm.isPlaying()) {
   delay(1);
}
   digitalWrite(6,HIGH);
   digitalWrite(5,LOW);
   tmrpcm.setVolume(6);
   tmrpcm.play("5.wav");

}
}

how can I make the wav play once but when the switch changes?

closed as unclear what you're asking by per1234, user31481, MatsK, KIIV, dhimaspw Feb 6 '18 at 3:58

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

0

Make a variable to hold the "last state" of the switch. Compare that last state to the current state as obtained by switchValue = digitalRead(8).

Only call the play function if the old value and the current value are different.

  • Hi I added this: if (switchValue != lastButtonState) { tmrpcm.setVolume(6); tmrpcm.play("4.wav"); while (tmrpcm.isPlaying()) { delay(1);} } lastButtonState = switchValue; I added it on both sides of my If Statement and It worked :-) – Moby1 Jan 31 '18 at 19:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.