User manual

LPCXpresso Experiment Kit - User’s Guide
Page 91
Copyright 2013 © Embedded Artists AB
7.13.3 Lab 12c: Timer IRQ with Callback
In this experiment the timer interrupt will call a registered function, called a callback function. It is a
commonly used program structure that can be very powerful and flexible.
Create a program that uses a timer callback to control flashing of a LED. Keep the breadboard setup
from the previous experiments (see Figure 13, page 39).
Study the code framework below. It outlines how a timer callback functionality can be implemented:
A function pointer to the callback function is stored.
A timer is setup to generate an interrupt after a specified time. After triggering the interrupt the
timer stops.
When the timer interrupts occurs, the callback function is called.
/* Declare function pointer (to a void-void function) for the callback function */
volatile void (*pCB)(void);
/* Define Interrupt Service Routine for 32-bit timer #1 */
void TIMER32_1_IRQHandler (void) //name of function is predefined
{
/* check if function pointer is value (not equal to NULL) */
if(pCB != NULL)
{
/* call function pointer = call callback function */
pCB(); //also valid syntax: (*pCB)();
/* invalidate function pointer */
pCB = NULL;
}
//stop timer
...
//clear timer interrupt
...
}
/*****************************************************************************
** Function name: registerCbAndDelay
** Descriptions: This function setup 32-bit timer #1 to generate
** an interrupt after specified time and then call a
** registered callback function.
** parameters: delay in ms and callback function pointer
** Returned value: None
**
*****************************************************************************/
void registerCbAndDelay( uint16_t delayInMS, void (*pF)(void))
{
/* register callback function */
pCB = pF;
/* setup timer to fire in ‘delayInMS’ ms */
...
/* enable 32-bit timer #1 interrupt */
NVIC_EnableIRQ(TIMER_32_1_IRQn);
}
/*****************************************************************************
** Function name: toggleLED
** Descriptions: This function toggles output PIO0_2
** Parameters: None
** Returned value: None
**
*****************************************************************************/
void toggleLED(void)
{
/* toggle LED on PIO0_2 */
...
}