gpt4 book ai didi

c - 如何在 Arduino Due 中创建精确的计时器

转载 作者:行者123 更新时间:2023-11-30 16:59:54 30 4
gpt4 key购买 nike

我正在尝试使用 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 或类似的东西。

您知道如何解决这个问题吗?我尝试添加 round() 来计算'counts'变量值,它有一点帮助,但仍然不是非常准确。

提前致谢。

最佳答案

我猜测 TC0 是一个 8 位定时器?如果只有 256 个选择,您将无法在“不寻常”的时间间隔内获得良好的精度。

尝试使用 16 位定时器。我在 GitHub 上看到了几个“到期计时器”,如果您需要的话。

根据我的计算:

获取预分频为 256 的 8 位除数:

84MHz / 3427 / 256 =  95.75 divisor, round to 96

生成

84MHz / 256 / 96 = 3,417.96 Hz

但是对于 16 位,没有预分频:

84MHz / 3427 =  24,511.23 divisor, truncate to 24511

生成

84MHz / 24511 = 3,427.03 Hz

由于计算出的除数 24511 适合 16 位值,因此您已经更接近您选择的比率。

当然,如果 TC0 实际上是一个 16 位定时器,那么还有其他问题! ;-) 祝你好运!

关于c - 如何在 Arduino Due 中创建精确的计时器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37918975/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com