Created
December 24, 2011 01:18
-
-
Save mikeash/1515865 to your computer and use it in GitHub Desktop.
Arduino driver for automatic audio switch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int inPins[2] = { 0, 1 }; | |
int lastValues[2] = { 0, 0 }; | |
float averages[2] = { 0, 0 }; | |
float delta = 0.0; | |
float decay = 0.02; | |
int outPin = 12; | |
unsigned long lastZeroTime = 0; | |
bool wasZero; | |
float zeroThreshold = 20.0; | |
unsigned long zeroResetTime = 5000; // milliseconds | |
void setup() | |
{ | |
Serial.begin(9600); | |
analogReference(INTERNAL); | |
pinMode(outPin, OUTPUT); | |
} | |
void loop() | |
{ | |
for(int i = 0; i < 2; i++) | |
{ | |
int val = analogRead(inPins[i]); | |
int diff = sqr(val - lastValues[i]); | |
lastValues[i] = val; | |
weightedAdd(&averages[i], diff); | |
Serial.print(diff); | |
Serial.print(" "); | |
} | |
weightedAdd(&delta, averages[1] - averages[0]); | |
if(averages[0] < zeroThreshold && averages[1] < zeroThreshold) | |
{ | |
unsigned long now = millis(); | |
if(wasZero) | |
{ | |
unsigned long zeroTime = now - lastZeroTime; | |
if(zeroTime > zeroResetTime) | |
{ | |
Serial.println("zeroed inputs"); | |
digitalWrite(outPin, LOW); | |
} | |
} | |
else | |
{ | |
lastZeroTime = now; | |
wasZero = true; | |
} | |
} | |
else | |
{ | |
wasZero = false; | |
} | |
if(!wasZero) | |
{ | |
float midpoint = (averages[0] + averages[1]) / 2; | |
if(averages[1] > averages[0] && delta > midpoint) | |
{ | |
Serial.print("LOW "); | |
digitalWrite(outPin, LOW); | |
} | |
else if(averages[0] > averages[1] && -delta > midpoint) | |
{ | |
Serial.print("HIGH "); | |
digitalWrite(outPin, HIGH); | |
} | |
Serial.print(averages[0]); | |
Serial.print(", "); | |
Serial.print(averages[1]); | |
Serial.print(" - "); | |
Serial.print(midpoint); | |
Serial.print(", "); | |
Serial.println(delta); | |
} | |
} | |
void weightedAdd(float *var, float newAmount) | |
{ | |
*var = (1.0 - decay) * *var + decay * newAmount; | |
} | |
int sqr(int x) | |
{ | |
return x * x; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment