-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ino
69 lines (60 loc) · 1.71 KB
/
main.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
#include <frequencyToNote.h>
#include <MIDIUSB.h>
#include <pitchToFrequency.h>
#include <pitchToNote.h>
#define LOOP_DELAY 1
#define ANALOG_CHANELS 6
#define THRESHOLD 100
#define MAX_VELOCITY 120
#define LEDPIN 13
uint16_t peak_total[ANALOG_CHANELS];
uint8_t peak_count[ANALOG_CHANELS];
uint8_t notes[ANALOG_CHANELS];
void setup() {
memset(peak_total, 0, sizeof(peak_total));
memset(peak_count, 0, sizeof(peak_count));
memset(notes, 0, sizeof(notes));
notes[0] = 36; // Bass Drum
notes[1] = 40; // Snare
notes[2] = 41; // Floor tom
notes[3] = 46; // Open Hi-Hat
notes[4] = 45; // Low tom
notes[5] = 49; // Crash 1
}
uint8_t getVelocity(uint16_t value) {
// rounding 1023(analogRead) int to an 127 (MIDIUSB) int velocity
uint8_t v = value / 8;
return v > MAX_VELOCITY ? MAX_VELOCITY : v;
}
void noteOn(uint8_t channel, uint8_t pitch, uint8_t velocity) {
digitalWrite(LEDPIN, HIGH);
midiEventPacket_t event = {0x09, 0x90 | channel, pitch, velocity};
MidiUSB.sendMIDI(event);
MidiUSB.flush();
}
uint16_t evalPeak(uint8_t index, uint16_t value){
if (value >= THRESHOLD) {
peak_total[index] += value;
peak_count[index] += 1;
return 0;
}
if (peak_count[index] > 0) {
uint16_t ret = (uint16_t)(peak_total[index] / peak_count[index]);
peak_total[index] = 0;
peak_count[index] = 0;
return ret;
}
return 0;
}
void readChannels(){
for (uint8_t i = 0; i < ANALOG_CHANELS; i++) {
uint16_t peakVelocity = evalPeak(i, analogRead(i));
if (peakVelocity > 0){
noteOn(i, notes[i], getVelocity(peakVelocity));
}
}
}
void loop(){
readChannels();
delay(LOOP_DELAY);
}