使用CTimer来产生100ms和1s标志位,用于在主循环中使用。
一、引脚。
GPIO中
二、代码。
#include "fsl_debug_console.h"
#include "board.h"
#include "fsl_ctimer.h"
#include "pin_mux.h"
#include #define CTIMER CTIMER2 /* Timer 2 */
#define CTIMER_MAT_OUT kCTIMER_Match_1 /* Match output 1 */
#define CTIMER_CLK_FREQ CLOCK_GetCTimerClkFreq(2U)
void ctimer2_callback(uint32_t flags);
volatile uint32_t g_pwmPeriod = 0U;
volatile uint32_t g_pulsePeriod = 0U;
static ctimer_callback_t ctimer_callback[] = {ctimer2_callback};volatile uint32_t gCtimer100msCnt = 0U;
volatile uint32_t gCtimer100msFlag = 0U;
volatile uint32_t gCtimer1sFlag = 0U;status_t CTIMER_GetPwmPeriodValue(uint32_t pwmFreqHz, uint8_t dutyCyclePercent, uint32_t timerClock_Hz) {g_pwmPeriod = (timerClock_Hz / pwmFreqHz) - 1;if (dutyCyclePercent == 0) {g_pulsePeriod = g_pwmPeriod + 1;} else {g_pulsePeriod = (g_pwmPeriod * (100 - dutyCyclePercent)) / 100;}return kStatus_Success;
}void ctimer2_callback(uint32_t flags) {gCtimer100msFlag = 1;if(gCtimer100msCnt > 9) {gCtimer1sFlag = 1;gCtimer100msCnt = 0;} else {gCtimer100msCnt++;}
}int main(void) {ctimer_config_t config;uint32_t timerClock;uint8_t flag1 = 0,flag2 = 0;CLOCK_AttachClk(BOARD_DEBUG_UART_CLK_ATTACH);CLOCK_AttachClk(kFRO_HF_to_CTIMER2);BOARD_InitPins();BOARD_BootClockPLL150M();BOARD_InitDebugConsole();CTIMER_GetDefaultConfig(&config);timerClock = CTIMER_CLK_FREQ / (config.prescale + 1);CTIMER_Init(CTIMER, &config);CTIMER_RegisterCallBack(CTIMER, &ctimer_callback[0], kCTIMER_SingleCallback);CTIMER_GetPwmPeriodValue(10, 50, timerClock); // 10Hz = 100ms中断一次CTIMER_SetupPwmPeriod(CTIMER, CTIMER_MAT_OUT, g_pwmPeriod, g_pulsePeriod, true);CTIMER_StartTimer(CTIMER);while (1) {if(gCtimer100msFlag == 1) {if(flag1 == 0) {GPIO_PinWrite(BOARD_INITPINS_OUT1_GPIO,BOARD_INITPINS_OUT1_PORT,BOARD_INITPINS_OUT1_PIN,0);flag1 = 1;} else {GPIO_PinWrite(BOARD_INITPINS_OUT1_GPIO,BOARD_INITPINS_OUT1_PORT,BOARD_INITPINS_OUT1_PIN,1);flag1 = 0;}gCtimer100msFlag = 0;} else if(gCtimer1sFlag == 1) {if(flag2 == 0) {GPIO_PinWrite(BOARD_INITPINS_OUT2_GPIO,BOARD_INITPINS_OUT2_PORT,BOARD_INITPINS_OUT2_PIN,0);flag2 = 1;} else {GPIO_PinWrite(BOARD_INITPINS_OUT2_GPIO,BOARD_INITPINS_OUT2_PORT,BOARD_INITPINS_OUT2_PIN,1);flag2 = 0;}gCtimer1sFlag = 0;}}
}
三、其它问题。
使用CTimer0、1、3、4时,发现
timerClock = CTIMER_CLK_FREQ / (config.prescale + 1);的CTIMER_CLK_FREQ为0,将其改为96000000即可。