We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I trigger a sound when a switch is flipped on an Arduino.
Unfortunatly the sound keeps looping and feeding back, presumably because the condition says to keep doing it until the switch is changed.
How do I get the sound to just play once each time the switch changes?
Here is my code:
import ddf.minim.*;
Minim minim;
AudioPlayer song;
import processing.serial.*;
Serial myPort; // Create object from Serial class
int val; // Data received from the serial port
void setup()
{
size(200, 200);
// I know that the first port in the serial list on my mac
// is always my FTDI adaptor, so I open Serial.list()[0].
// On Windows machines, this generally opens COM1.
// Open whatever port is the one you're using.
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
minim = new Minim(this);
}
void draw()
{
if ( myPort.available() > 0) { // If data is available,
val = myPort.read(); // read it and store it in val
}
background(255); // Set background to white
if (val == 0) { // If the serial value is 0,
fill(0); // set fill to black
text("button is '0'",10,30);
// this loads first noise from the data folder
song = minim.loadFile("btn06.mp3");
song.play();
}
if (val == 1) { // If the serial value is not 0,
fill(204); // set fill to light gray
text("button is '1'",10,30);
// this loads second noise from the data folder
song = minim.loadFile("btn08.mp3");
song.play();
}
rect(50, 50, 100, 100);
}
Answers
Beware, once val has a value of 0 or 1, as long as it has this value, you attempt to load a MP3 file on each call of draw(), ie. some 60 times per second.
You should have two song variables, load them in setup() instead, and play them when the state change, not on a value of state. So, perhaps keep the previous value of val, and compare the new value with the old one: only when they are different, trigger the sound. Don't forget to assign the new value to the old one just after.
That makes sense, thanks!. I've tried to do something similar but can't seem to figure out a conditional statement that runs IF the variable changes from one string to another (switchOnePosition goes from "state 0" to "state 1" for example).
The code below shows what I currently have:
Fixed it, I needed three states for the switch variable (off, playsnd and waiting), this combined with IFF AND statements that combine the switch value and the variable state result in the sound being played only once.
Incase any other beginners are puzzled by the same, here's the code I used:
Data type String isn't appropriate for "state" variables! Especially when using operator
==
to check them out!Instead, use
int
constants to represent those states.And since switchOnePosition only got 2 states,
boolean
is pretty enough! :Dhttp://processing.org/reference/boolean.html
What I had in mind (untested):