Created
August 26, 2017 05:22
-
-
Save ttatsf/d81ae3adf0aab8230907e81f67bea8ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
constexpr int NUM_BUTTONS ( 4 ); //buttonの数 | |
constexpr int LED_PIN ( 13 ); // LEDのピン | |
constexpr int GND_PINS[ NUM_BUTTONS ] { 5, 7, 9, 11 }; //結線の都合でGNDとして使用 | |
// Button構造体の定義 | |
struct Button{ | |
const int PIN; | |
const int CC_NUM; | |
long innerMul100; | |
bool debouncedPrev; | |
bool doPrev; | |
Button(int pin, int cc) : PIN ( pin ) | |
, CC_NUM ( cc ) | |
, innerMul100 ( 100 ) | |
, debouncedPrev ( true ) | |
, doPrev ( false ) { | |
} | |
}; | |
// Buttonオブジェクトの配列を作る | |
Button BUTTONS[ NUM_BUTTONS ] { Button( 4, 25 ) | |
, Button( 6, 28 ) | |
, Button( 8, 27 ) | |
, Button(10, 26 ) | |
}; | |
// データをデバウンスして返す関数。 | |
// 履歴を引数bのb.innerMul100、b.debouncePrev を書き換えて残す。 | |
auto debounce ( | |
[](Button& b, const bool& CURRENT_RAW ) -> bool{ | |
constexpr auto RATE ( 12 ); | |
constexpr auto THRESHOLD_L ( 10 ); | |
constexpr auto THRESHOLD_H ( 90 ); | |
b.innerMul100 = RATE * CURRENT_RAW + (100 - RATE) * b.innerMul100 / 100; | |
if( b.debouncedPrev ) { | |
if( b.innerMul100 < THRESHOLD_L ) return b.debouncedPrev = false; | |
return true; | |
} | |
if( b.innerMul100 > THRESHOLD_H ) return b.debouncedPrev = true; | |
return false; | |
} | |
); | |
// MIDI Control Changeを出力する関数。 | |
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 ); | |
} | |
); | |
// データによって何かする関数。 | |
// 履歴を引数bのb.doPrevを書き換えて残す。 | |
auto doByData ( | |
[]( Button& b, const bool& DATA ) -> bool{ | |
if( b.doPrev && ! DATA ){ | |
txMidiCC( b.CC_NUM, 127); | |
digitalWrite( LED_PIN, HIGH ); | |
return b.doPrev = DATA; | |
} | |
if( ! b.doPrev && DATA ){ | |
txMidiCC( b.CC_NUM, 0); | |
digitalWrite( LED_PIN, LOW ); | |
return b.doPrev = 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 ){ | |
doByData( b , debounce( b , digitalRead( b.PIN ) | |
) ); | |
} | |
delay( 2 ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment