-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaudio-detector.ino
executable file
·78 lines (57 loc) · 1.62 KB
/
audio-detector.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const long maxIdleMinutes = 1;
const int ON_TIMEOUT = 10000;
const int OFF_TIMEOUT = 1000;
int sampleSleepTime = OFF_TIMEOUT;
const int playingPin = 2;
const int playingPin2 = LED_BUILTIN;
const int leftInput = A0;
const int rightInput = A1;
#define ANALOG_SAMPLES 20
const int analogThreashold = 2; // Less than this is noise
long lastPlayingTimestamp = 0;
bool IsMusicPlaying()
{
int maxRead = 0;
int samples[ANALOG_SAMPLES];
int i;
// Take samples on right channel
for(i=0; i < (sizeof(samples)/sizeof(samples[0])); i++)
{
samples[i] = analogRead(leftInput);
delay(2 * i);
}
for(i=0; i < (sizeof(samples)/sizeof(samples[0])); i++)
if (samples[i] > maxRead)
maxRead = samples[i];
// Take samples on left channel
for(i=0; i < (sizeof(samples)/sizeof(samples[0])); i++)
{
samples[i] = analogRead(leftInput);
delay(2 * i);
}
for(i=0; i < (sizeof(samples)/sizeof(samples[0])); i++)
if (samples[i] > maxRead)
maxRead = samples[i];
return (maxRead > analogThreashold);
}
void setup()
{
pinMode(playingPin, OUTPUT);
pinMode(playingPin2, OUTPUT);
}
void loop()
{
if (IsMusicPlaying()) {
digitalWrite(playingPin, HIGH);
digitalWrite(playingPin2, HIGH);
lastPlayingTimestamp = millis();
sampleSleepTime = ON_TIMEOUT;
} else {
if (millis() - lastPlayingTimestamp > maxIdleMinutes * 1000 * 60) {
digitalWrite(playingPin, LOW);
digitalWrite(playingPin2, LOW);
sampleSleepTime = OFF_TIMEOUT;
}
}
delay(sampleSleepTime);
}