NXP MCU 技术论坛
直播中

juju宇哥

9年用户 1474经验值
擅长:479809
私信 关注
[问答]

请分享Ctimer计数器捕获程序的示例程序

我目前正在研究 OM13098LPCxpresso54628 开发板。请分享 Ctimer 计数器捕获程序的示例程序,或者配置 ctimer 每 1 秒捕获一次输入脉冲所涉及的步骤是什么。

回帖(1)

洪茗苞

2024-6-4 16:52:21
以下是一个使用Ctimer计数器捕获输入脉冲的示例程序:

```c
#include "board.h"

#define CTIMER_CLK_FREQ (20971520UL)

void ctimer_init(void)
{
    /* Enable the clock for CTIMER0 */
    clock_enable_clock(LPC_CTIMER0);

    /* Set the prescaler to generate 1 MHz clock */
    CTIMER0->PR = (CTIMER_CLK_FREQ / 1000000UL) - 1;

    /* Set the match register 0 to generate a match every second */
    CTIMER0->MR0 = 1000000 - 1;

    /* Reset the timer counter and the prescaler */
    CTIMER0->TCR |= CTIMER_TCR_CR;

    /* Enable the interrupt for match register 0 */
    CTIMER0->MCR |= (1 << CTIMER_MCR_MR0I);

    /* Start the timer */
    CTIMER0->TCR |= CTIMER_TCR_CE;
}

void ctimer_capture_init(void)
{
    /* Enable the clock for CTIMER3 */
    clock_enable_clock(LPC_CTIMER3);

    /* Set P1.11 as CTIMER3_CAP3 */
    PinSetMode(PIN_1_11, PIN_CAP3);

    /* Set the prescaler for CTIMER3 to generate 1 MHz clock */
    CTIMER3->PR = (CTIMER_CLK_FREQ / 1000000UL) - 1;

    /* Set CTIMER3 to count on rising edges on CAP3 */
    CTIMER3->CCR |= (1 << CTIMER_CCR_CAP3RE);

    /* Enable the interrupt for CTIMER3 */
    NVIC_EnableIRQ(CTIMER3_IRQn);

    /* Start the timer */
    CTIMER3->TCR |= CTIMER_TCR_CE;
}

uint32_t ctimer_get_capture(void)
{
    return CTIMER3->CR3;
}

void ctimer_reset_capture(void)
{
    CTIMER3->CCR |= (1 << CTIMER_CCR_CAP3R);
}

void CTIMER3_IRQHandler(void)
{
    /* If a capture occurred, reset the capture register */
    if (CTIMER3->IR & (1 << CTIMER_IR_CR3INT))
    {
        CTIMER3->IR |= (1 << CTIMER_IR_CR3INT);
        ctimer_reset_capture();
    }
}

int main(void)
{
    ctimer_init();
    ctimer_capture_init();

    while (1)
    {
        /* Wait for a capture event */
        while (!(CTIMER3->IR & (1 << CTIMER_IR_CR3INT)));

        /* Get the captured value and do something with it */
        uint32_t capture_val = ctimer_get_capture();
        // Do something with capture_val
    }
}
```

该程序使用CTIMER0定时器来生成匹配事件,从而触发CTIMER3计数器进行捕获。CTIMER3计数器通过设置CCR寄存器,使它在每个上升沿上捕获输入脉冲。捕获发生后,将在CTIMER3中断处理程序中重置捕获寄存器,并在主循环中使用捕获值进行操作。
举报

更多回帖

发帖
×
20
完善资料,
赚取积分