I'm trying to sync a MIDI external clock to a sequencer I've made with a display and a raspberryPi Pico.
I got everything working but there is something I don't understand.
The code:
#include <Adafruit_TinyUSB.h>
#include <MIDI.h>
using namespace midi;
MIDI_CREATE_INSTANCE(HardwareSerial, Serial1, MIDI_DIN)
void setup(){
MIDI_DIN.begin(0);
}
void loop(){
if (MIDI_DIN.read())
{
// switch (mode ? MIDI_USB.getType() : MIDI_DIN.getType())
switch (MIDI_DIN.getType())
{
case midi::Clock:
{
static int ticks = 0;
if (ticks++ >= clockDiv)
{
static int sequencerIndex = 0;
Serial.println(sequencerIndex++);
if(sequencerIndex > 15){
sequencerIndex = 0;
}
ticks = 0;
}
static unsigned long previousClock = 0;
unsigned long currentClock = micros();
static int bpmTicks = 0;
if (bpmTicks++ >= 24)
{
// Calcul du delta entre les pulses MIDI Clock
unsigned long delta = currentClock - previousClock;
bpm = (bpm + (63000000 / delta)) / 2; // 1us in sc => 1000000, delta in us, by minute (1000000/delta) * 60
previousClock = currentClock;
bpmTicks = 0;
}
break;
}
}
}
This code is working when syncing with an external machine (Digitakt).
The problem is, the sequencerIndex is perfectly synced with the external machine step ONLY if the clockDiv is equal to 5, and I can't understand why this number.
When I try to double or divide this clockDiv by a 2 factor, the sequencer is not speeded or slowed by 2. The spped doesn't seem to be synced anymore to the external gear.