Skip to content

Instantly share code, notes, and snippets.

@billju
Last active October 21, 2021 01:58
Show Gist options
  • Save billju/ce1337ea3c1dbb4341ce22dca1b55442 to your computer and use it in GitHub Desktop.
Save billju/ce1337ea3c1dbb4341ce22dca1b55442 to your computer and use it in GitHub Desktop.
/*
Super Easy Diy Drumpad Example
GIT: https://gist.github.com/billju/ce1337ea3c1dbb4341ce22dca1b55442
2017 by Billju
Inspired by Evan Kale
*/
#include <Keyboard.h>
#include "MIDIUSB.h"
#define NUM_PIEZOS 7
#define NUM_CONTROL 2
#define TIME_BETWEEN_NOTES 50
#define TIME_BETWEEN_PEAKS 20
#define Signal_Fetch 6
#define switch_pin 7
unsigned short noteMap[NUM_PIEZOS]={49,47,45,48,38,44,36};
const int slotMap[NUM_PIEZOS]={A0,A1,A2,A3,A4,A5,A11};
const int MAX_velocity[NUM_PIEZOS]= {60,60,60,60,60,60,10};
const int Threshold[NUM_PIEZOS]={6,6,6,6,6,6,1};
int key[NUM_PIEZOS]={'v',216,'c',215,'x','z',13};
bool NoteOn[NUM_PIEZOS];
bool counting[NUM_PIEZOS];
unsigned short NewPeak[NUM_PIEZOS][Signal_Fetch];
unsigned short Peak[NUM_PIEZOS];
unsigned short index[NUM_PIEZOS];
unsigned long lastPeakTime[NUM_PIEZOS];
unsigned long lastNoteTime[NUM_PIEZOS];
unsigned short value[NUM_CONTROL];
unsigned short lastvalue[NUM_CONTROL];
bool switch_state;
void setup()
{
Serial.begin(115200);
pinMode(7,INPUT);
for(short i=0; i<NUM_PIEZOS; ++i){
NoteOn[i] = 0;
Peak[i] = 0;
index[i]= 0;
counting[i]= 0;
for(int j=6;j<6;j++){NewPeak[i][j]=0;}
}
Keyboard.begin();
}
void loop(){
switch_state=digitalRead(switch_pin);
for(short i=0; i<NUM_PIEZOS; i++)
{
unsigned short newSignal = analogRead(slotMap[i]);
if(NoteOn[i] == 0){
if(newSignal > Threshold[i] && counting[i]==0){lastPeakTime[i]=millis();counting[i]=1;}
else if(newSignal > Threshold[i] && counting[i]==1 && millis()-lastPeakTime[i] < TIME_BETWEEN_PEAKS){
if(index[i] < Signal_Fetch)
{ NewPeak[i][index[i]]=newSignal;index[i]++;}
}
else if(counting[i]==1 && millis()-lastPeakTime[i] > TIME_BETWEEN_PEAKS)
{ counting[i]=0;
for(int j=0;j<Signal_Fetch;j++){
if(NewPeak[i][j] > Peak[i])
Peak[i]=NewPeak[i][j];
}
if(Peak[i]>MAX_velocity[i]){Peak[i]=MAX_velocity[i];}
int velocity=map(Peak[i],0,MAX_velocity[i],60,127);
midiNoteOn(noteMap[i], velocity);
if(switch_state==HIGH)
Keyboard.press(key[i]);
NoteOn[i]= 1;
Peak[i]=0;
index[i]=0;
for(int j=6;j<6;j++){NewPeak[i][j]=0;}
lastNoteTime[i]=millis();
}
}
if(NoteOn[i]== 1 && millis() - lastNoteTime[i] > TIME_BETWEEN_NOTES){
midiNoteOff(noteMap[i], 60);
if(switch_state==HIGH)
Keyboard.release(key[i]);
NoteOn[i]= 0;
}
}
}
void midiNoteOn(byte note, byte midiVelocity){
midiEventPacket_t noteOn = {0x09, 0x90 | 0, note, midiVelocity};
MidiUSB.sendMIDI(noteOn);
MidiUSB.flush();
}
void midiNoteOff(byte note, byte midiVelocity){
midiEventPacket_t noteOff = {0x08, 0x80 | 0, note, midiVelocity};
MidiUSB.sendMIDI(noteOff);
MidiUSB.flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment