From 2a4670009b60103728b834900a90d800733e3f32 Mon Sep 17 00:00:00 2001 From: Peter Cai Date: Fri, 11 Jun 2021 10:23:53 +0800 Subject: [PATCH] limit frequency of reading & parsing MIDI data To improve note accuracy --- main.cpp | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/main.cpp b/main.cpp index e7abf25..86fd304 100644 --- a/main.cpp +++ b/main.cpp @@ -5,6 +5,10 @@ #define NUM_MOTORS 4 +// Minimal interval between reading two chunks of MIDI data +// This improves frequency accuracy by throttling non-synthesizing actions +#define MIDI_CMD_INTERVAL_MIN 15 * 1000 // 15ms + using namespace midi; MotorControl motors[NUM_MOTORS] = { @@ -73,10 +77,24 @@ int main() { MIDI.setHandleNoteOn(midi_note_on); MIDI.setHandleNoteOff(midi_note_off); + unsigned long cur_micros; + unsigned long last_read_micros = 0; + while (true) { - unsigned long cur_micros = timer2.get_count() / 2ul; // The unit of get_count is 0.5us + cur_micros = timer2.get_count() / 2ul; // The unit of get_count is 0.5us handle_tick(cur_micros); - MIDI.read(); + + if (cur_micros - last_read_micros >= MIDI_CMD_INTERVAL_MIN) { + last_read_micros = cur_micros; + + // Read all available MIDI data + // Note that the host is expected to send MIDI data only when + // it is supposed to be played; therefore we don't need + // to worry about the host sending data prematurely + while (Serial.available()) { + MIDI.read(); + } + } } return 0;