Hello everyone! Would someone have some code to share that does clock multiplication? In other words, it takes a clock input (processed using a dsp::SchmittTrigger) and outputs subdivisions of the input clock?
For some reason, my code almost does it, but can start to “swing” or “groove”.
Here’s my code:
#include <iostream>
#include <cmath> // for std::floor, std::abs
class ClockModifier
{
private:
double time_between_clocks_ms = 0.0; // Time between incoming clock pulses in milliseconds
int division_factor = 1; // Clock division factor
int multiplication_factor = 1; // Clock multiplication factor
double accumulated_time_ms = 0.0;
double previous_trigger_output_time = 0.0;
double previous_clock_time = 0.0;
unsigned int clock_division_counter = 0;
public:
// Called when a clock pulse happens
void clockMultiply(float rate_index, double time_now)
{
multiplication_factor = rate_index;
if (previous_clock_time == 0.0)
{
previous_clock_time = time_now;
return;
}
time_between_clocks_ms = time_now - previous_clock_time;
previous_clock_time = time_now;
}
// Should a clock pulse be emitted?
bool process(double time_now)
{
accumulated_time_ms = time_now - previous_trigger_output_time;
double target_time = time_between_clocks_ms / multiplication_factor;
if (accumulated_time_ms >= target_time)
{
accumulated_time_ms -= target_time;
previous_trigger_output_time = time_now;
return true;
}
return false;
}
bool clockDivide(unsigned int clock_division)
{
if(clock_division == 0) clock_division = 1;
clock_division_counter++;
if (clock_division_counter >= clock_division)
{
clock_division_counter = 0;
return true; // Emit a new clock pulse
}
else
{
return false; // Do not emit a new clock pulse
}
}
};
Thanks!