I have a timer setup that is triggering and reading the iPhone mic input level. I have some if statements that say if the incoming volume is "this" then change the views background color to "this".
Everything works okay but naturally the meter goes in succession of 0,1,2,3,4,5 then back down in the reverse order of 5,4,3,2,1,0. However I do not want this to occur. I want to jump all the way back to "0" when the volume tries to go back down.
So what I did, was create two variables. One called "previousValue" and the other "currentValue" to keep track of where they are in the succession of levels I am at - then one last if statement that says if previousValue > currentValue (going down) then jump back to "0". However, it's just not working. Maybe I am doing something wrong here?
A little help would be very appreciated! Thank you! Here is the code so you can get a better look at what I am trying to achieve.
I declare the INT values below the implementation int previousValue; int currentValue;
then set a starting point in the viewDidLoad previousValue = 0; currentValue = 0;
if (meterResults > 0.0) {
NSLog(@"0");
self.view.backgroundColor = [UIColor redColor];
previousValue = currentValue;
currentValue = 0;
}
if (meterResults > 0.1){
NSLog(@"1");
self.view.backgroundColor = [UIColor yellowColor];
previousValue = currentValue;
currentValue = 1;
}
if (meterResults > 0.2){
NSLog(@"2");
self.view.backgroundColor = [UIColor blueColor];
previousValue = currentValue;
currentValue = 2;
}
if (meterResults > 0.3){
NSLog(@"3");
self.view.backgroundColor = [UIColor greenColor];
previousValue = currentValue;
currentValue = 3;
}
if (meterResults > 0.4){
NSLog(@"4");
self.view.backgroundColor = [UIColor purpleColor];
previousValue = currentValue;
currentValue = 4;
}
if (previousValue > currentValue) {
NSLog(@"Hello, don't go in reverse order go straight to Red");
self.view.backgroundColor = [UIColor redColor];
}
Aroth's answer is right, but you'll still have a problem after you take the advice. Since you're sampling an analog signal, successive measurements will be roughly continuous. If you change the current value to zero, the next value read will appear to your code to be increasing again, which it isn't.
Don't lie about the current value to make the UI behave as you wish. Instead, model the thing you care about explicitly, which is the instantaneous first derivative. That would go like this:
currentValue = (int)floor(meterResults * 10.0);
NSInteger currentFirstDerivative = currentValue - previousValue;
// since the timer repeats at a fixed interval, this difference is like a 1st derivative
if (currentFirstDerivative < 0) {
// it's going down, make the view red
} else {
switch (currentValue) {
case 1:
// change colors here
break;
case 2:
// and so on
}
// now, for next time
previousValue = currentValue;