Hello All,
I'm running into a wall on what I thought would be a pretty simple program.
I'll try to briefly describe what I'd like the sketch to do, then post the code with comments.
I'd like to continuously take readings from a force-sensing resistor.
If the reading is above a threshold, I'd like to tell the MP3 trigger to start playing.
As long as the sensor keeps getting relatively frequent readings above 0 (or some other arbitrary threshold),
I'd like it to keep playing. If the sensor gets no readings for a set period of time (3 seconds or so?) I'd like the trigger to stop playing.
Simple, right? Well, not for me, it turns out.
To determine if the sensor had received a number of consecutive zeros, I put in two arrays. One to store the sensor values and one of nothing but zeros.
I then wrote a simple boolean function to continuously compare the two arrays. If the arrays are equal (meaning, both are all zero), that should mean that
the sensor received no readings for a while.
As far as I can tell, the code below should do what I described, but it does not. When the trigger starts playing a track it just keeps on playing, no matter how many zeros.
I have two questions for the forum:
- Is there anything in my code that would cause this unexpected result ( I admit I'm not great with programming)??
- Is creating two arrays to determine if and when the sensor gets no reading a good way to do it? I would imagine there is a simpler or more elegant way of achieving this, but two arrays is my best guess so far.
I'd really appreciate any help on this. Many Thanks!
Here's the code:
/*Continuously read analog sensor values and compare them to an equal-sized
array of zeros. Serially communicate with Robertsonics MP3Trigger*/
#define SENSOR 0 //In this case, a force-sensing resistor
int num = 30;
int val[30]; //array of sensor values
int zero[30]; //array of zeros
boolean isPlaying;
void setup() {
Serial.begin(38400);
}
void loop() {
int threshold = 20;
int i;
for (i = 0; i < num; i = i + 1) {
val[i]=analogRead(SENSOR); //store sensor values
zero[i] = 0; //store zeros
delay(200);
Serial.println(val[i]);
if((val[i] >= threshold) && (isPlaying == false)) {
Serial.write('p'); //Serial command for playing a track
Serial.write(1); //track number
isPlaying == true;
delay(3000);
}
}
if ((arrayCompare(val, zero, num, num)==true) && (isPlaying==true)) { /* if 30 consecutive
sensor values = 0*/
Serial.write('O'); //Serial command for stop/start
isPlaying == false;
}
}
boolean arrayCompare(int x[], int y[], int len_x, int len_y) { /*compare sensor values to
array of zeros. Return true
if all sensor values = 0 */
int i;
for(i = 0; i < len_x; i++) {
if (x[i] == y[i]) {
return true;
}
return false
}
}