-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheleDeej.ino
124 lines (102 loc) · 2.66 KB
/
eleDeej.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const uint8_t analogInputs[] = {A0, A1, A2, A3}; // connected arduino pins
const String deejName = "deej"; // descriptive and unique name of your deej
const bool revert = true; // revert the values eg. 1023 -> 0
// the size of the average window as exponent (the window size will be 2^N_EXP)
const int N_EXP = 7;
const int NUM_SLIDERS = sizeof(analogInputs) / sizeof(uint8_t);
// slider average value expressed in fixed point arithmetic (multiplier 2^53)
typedef uint64_t FixedFract;
const unsigned int MUL_EXP = 53; // the default mul is 2^53 as the pin values are < 2^10 and 2^10 * 2^53 < 2^64
FixedFract analogSliderAvg[NUM_SLIDERS];
inline FixedFract toFixedPoint(int val)
{
return ((FixedFract)val) << MUL_EXP;
}
inline FixedFract mapToRange(FixedFract val, int oldMax, int newMax)
{
return (val / oldMax) * newMax + (toFixedPoint(1) >> 1);
}
inline int roundToInt(FixedFract val)
{
// value + 0.5 so trunc to int will round to closes number
FixedFract rounded = val + (1 << (MUL_EXP - 1));
return rounded >> MUL_EXP;
}
void setup()
{
for (int i = 0; i < NUM_SLIDERS; i++)
{
pinMode(analogInputs[i], INPUT);
analogSliderAvg[i] = 0;
}
Serial.begin(9600);
}
String readString = "";
String command = "";
void loop()
{
// read all the available characters from the serial up to the new line character
char lastChar;
while (Serial.available() > 0 && (lastChar = Serial.read()) != '\n')
{
readString += lastChar;
}
// if new line is read then copy buffer to the command
if (lastChar == '\n')
{
command = readString;
readString = "";
}
// update slider values
updateSliderValues();
// perform the commands
if (command == "desc")
{
Serial.println(deejName);
}
if (command == "vol")
{
sendSliderValues();
}
// clean the command
if (command.length() > 0)
{
command = "";
}
delay(1);
}
void updateSliderValues()
{
for (int i = 0; i < NUM_SLIDERS; i++)
{
int newSample = analogRead(analogInputs[i]);
// update moving average
if (analogSliderAvg[i] == -1)
{
analogSliderAvg[i] = toFixedPoint(newSample);
}
else
{
analogSliderAvg[i] -= analogSliderAvg[i] >> N_EXP;
analogSliderAvg[i] += toFixedPoint(newSample) >> N_EXP;
}
}
}
void sendSliderValues()
{
String builtString = String("");
for (int i = 0; i < NUM_SLIDERS; i++)
{
int printVal = roundToInt(mapToRange(analogSliderAvg[i], 1023, 100));
if (revert)
{
printVal = 100 - printVal;
}
builtString += String(printVal);
if (i < NUM_SLIDERS - 1)
{
builtString += String("|");
}
}
Serial.println(builtString);
}