Arduino Due で TC タイマーを使用して PWM 波を作成しようとしています。私の問題は、この種のタイマーを使用して正確な周波数を生成できないことです。
これが私がやろうとしていることの簡単なコードです:
static void setupTimer(uint32_t freq_desired)
{
uint32_t ul_div;
uint32_t ul_tcclks;
uint32_t ul_sysclk = sysclk_get_cpu_hz();
uint32_t counts;
// Configure PMC
pmc_enable_periph_clk(ID_TC);
// Configure TC for the given frequency and trigger on RC compare.
tc_find_mck_divisor(
(uint32_t)freq_desired, // The desired frequency as a uint32.
ul_sysclk, // Master clock freq in Hz.
&ul_div, // Pointer to register where divisor will be stored.
&ul_tcclks, // Pointer to reg where clock selection number is stored.
ul_sysclk); // Board clock freq in Hz.
tc_init(TC0, CHANNEL, ul_tcclks | TC_CMR_CPCTRG);
// Find the best estimate of counts, then write it to TC register C.
counts = (ul_sysclk/ul_div)/freq_desired;
tc_write_rc(TC0, 0, counts);
// Enable interrupts for this TC, and start the TC.
tc_enable_interrupt(TC0, CHANNEL0, TC_IER_CPCS); // Enable interrupt.
tc_start(TC0,CHANNEL0); // Start the TC.
NVIC_DisableIRQ(TC_IRQn);
NVIC_ClearPendingIRQ(TC_IRQn);
NVIC_SetPriority(TC_IRQn,configMAX_PRIORITIES);
NVIC_EnableIRQ(TC_IRQn);
}
次に、タイマーのハンドルで、次のように出力ピンをトリガーします。
ioport_toggle_pin_level(OUT_PIN);
問題は、たとえば 1000Hz の波を生成しようとすると (もちろんタイマーに 2000Hz を与える)、正常に動作することです。しかし、3427Hzのように試してみると、3420Hzまたはそのようなものしか生成されません。
それを修正する方法を教えてください。「counts」変数値を計算するために round() を追加しようとしましたが、少しは役に立ちましたが、まだ非常に正確ではありません。
前もって感謝します。