Skip to content

Instantly share code, notes, and snippets.

@ttatsf
Created August 26, 2017 05:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttatsf/c6f99551ff5e14836637ff23b9bf59de to your computer and use it in GitHub Desktop.
Save ttatsf/c6f99551ff5e14836637ff23b9bf59de to your computer and use it in GitHub Desktop.
constexpr int NUM_BUTTONS ( 4 );
constexpr int LED_PIN ( 13 );
constexpr int GND_PINS[ NUM_BUTTONS ] { 5, 7, 9, 11 };
class Debounce{
static constexpr long RATE = 12;
static constexpr long THRESHOLD_L = 10;
static constexpr long THRESHOLD_H = 90;
long innerMul100;
bool debouncedValue;
public:
Debounce():innerMul100( 100 ), debouncedValue( true ){};
auto operator()( const bool& CURRENT_RAW )->bool{
innerMul100 = RATE * CURRENT_RAW + (100 - RATE) * innerMul100 / 100;
if( debouncedValue ) {
if( innerMul100 < THRESHOLD_L ) return debouncedValue = false;
return true;
}
if( innerMul100 > THRESHOLD_H ) return debouncedValue = true;
return false;
};
};
class IsRaised{
bool previousValue;
public:
IsRaised():previousValue ( false ) {}
auto operator()(const bool DATA)->bool{
const bool RESULT ( ! previousValue && DATA );
previousValue = DATA;
return RESULT;
}
};
class IsDropped{
bool previousValue;
public:
IsDropped():previousValue ( false ) {}
auto operator()(const bool DATA)->bool{
const bool RESULT ( previousValue && ! DATA );
previousValue = DATA;
return RESULT;
}
};
struct Button{
const int PIN;
const int VAL;
Debounce debounce;
IsRaised isRaised;
IsDropped isDropped;
Button(int pin, int val) : PIN(pin)
, VAL(val)
, debounce()
, isRaised()
, isDropped(){
}
};
Button BUTTONS[ NUM_BUTTONS ] { Button( 4, 25 )
, Button( 6, 28 )
, Button( 8, 27 )
, Button(10, 26 )
};
auto txMidiCC (
[](const int& CC_NUM, const int& VALUE){
constexpr auto MESSAGE ( 176 ); //CC (channel:0)
Serial.write( MESSAGE );
Serial.write( CC_NUM );
Serial.write( VALUE );
}
);
auto doWhenDropped (
[]( Button& b, const bool& DATA ){
if( b.isDropped( DATA ) ){
txMidiCC( b.VAL, 127);
digitalWrite( LED_PIN, HIGH );
return DATA;
}
return DATA;
}
);
auto doWhenRaised (
[]( Button& b, const bool& DATA ){
if( b.isRaised( DATA ) ){
txMidiCC( b.VAL, 0);
digitalWrite( LED_PIN, LOW );
return DATA;
}
return DATA;
}
);
void setup() {
pinMode( LED_PIN, OUTPUT );
for ( const auto& b : BUTTONS ) {
pinMode( b.PIN, INPUT_PULLUP );
}
for( const auto& p : GND_PINS ) {
pinMode( p, OUTPUT );
digitalWrite( p, LOW );
}
Serial.begin( 31250 );
}
void loop() {
for (auto&& b : BUTTONS ){
doWhenRaised( b, doWhenDropped( b, b.debounce( digitalRead( b.PIN )
) ) );
}
delay( 2 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment