Hello,
I am currently trying to have a simple duty cycle measurement functionality using Timer0 capture 2.
Initialization /code
I have initialized the timer as follows:
//defines
#define SMT_timer LPC_TIMER0
#define SMT_IRQ TIMER0_IRQn
#define SMT_RGU RGU_TIMER0_RST
#define SMT_timerNR 0
#define SMT_capNR 2
#define SMT_CLK_MX CLK_MX_TIMER0
#define TIMER0TICKRATEHZ 30000000 //try to be at least 2x7 kHz
/* Enable timer clock and reset it */
Chip_TIMER_Init( SMT_timer );
Chip_RGU_TriggerReset(SMT_RGU);
while (Chip_RGU_InReset(SMT_RGU)) {}
/* Get timer 0 peripheral clock rate */
uint32_t timerFreq;
timerFreq = Chip_Clock_GetRate(SMT_CLK_MX);
/* Timer setup for match and interrupt at TIMER0TICKRATE_HZ */
Chip_TIMER_Reset(SMT_timer);
Chip_TIMER_MatchEnableInt(SMT_timer, SMT_timerNR);
Chip_TIMER_SetMatch(SMT_timer, SMT_timerNR, (timerFreq / TIMER0TICKRATEHZ));//SMT_timerNR could need to be 1
Chip_TIMER_ResetOnMatchEnable(SMT_timer, SMT_timerNR);
// Chip_TIMER_Enable(LPC_TIMER0); //only done during measurement
/* Set input capture */
// Chip_TIMER_Reset( SMT_timer );
Chip_TIMER_CaptureEnableInt(SMT_timer, SMT_capNR); //Capture on T0_CAP2 (BUSY_SMT)
// LPC_GIMA->CAP0_IN[SMT_timerNR][SMT_capNR] = 3<<4 | 1<<2; //capture source T3_CAP2
LPC_GIMA->CAP0_IN[SMT_timerNR][SMT_capNR] = 0x20; //0x20 = the T0Cap2 pin in input selection
/* Set interrupt priority */
NVIC_SetPriority(SMT_IRQ, 2);
The timer only gets started when I want to measure the duty cycle in this manner:
/* Enable Timer */
Chip_TIMER_Reset( SMT_timer );
Chip_TIMER_CaptureRisingEdgeDisable(SMT_timer, 2);//start looking for a falling edge
Chip_TIMER_CaptureFallingEdgeEnable(SMT_timer, 2);
Chip_TIMER_ClearCapture(SMT_timer, 2);
Chip_TIMER_Enable( SMT_timer );
/* Enable interrupt */
NVIC_EnableIRQ(SMT_IRQ);
NVIC_ClearPendingIRQ(SMT_IRQ);
From then on, the IRQ handles the measurement.
void SMT_IRQ_handler()
{
if (Chip_TIMER_CapturePending(SMT_timer, 2))//if something was captured
{
Chip_TIMER_ClearCapture(SMT_timer, 2);
capvalue0_SMT = Chip_TIMER_ReadCapture(SMT_timer, 2);
/* ........... */
}
}
The issue
The capvalue keeps finding very odd numbers, which do not line up sequentially. E.g capture value 1 = 5, then the next captured value is 1, etc.
The captured edges are correct as I have checked this on an oscilloscope, adding an external trigger (channel 1) pin that is set high when a measurement starts, and gets pulled low when 8 periods are measured (this signal is connected to channel 2). I can count the 8 periods that I wish to measure.
I do not think the unsigned int holding the time is flipping inbetween each capture as even at the highest frequency (204MHz) the timer should still be able to track 21s before flipping. But I am completely lost as to what could be my issue here.
Is there a way for the timestamps to be overwritten somehow?
I hope my question was somewhat clear and I appreciate any form of tips and help I can get!