The following shows yet another bare-bones busy-wait style delay using the PIT for accuracy.
Note that such busy-wait loops are not a good idea in real programs.
/*
=====================================================================================
* main.c
*
* Created on: 12/05/2013
* Author: podonoghue
*
* Simple demonstration of PIT busy-wait
*
====================================================================================
*/
#include "derivative.h"
#include "clock.h"
#define SYSTEM_CLOCK_FREQUENCY (48000000UL)
#define PIT_CLOCK_FREQUENCY SYSTEM_CLOCK_FREQUENCY
#define PIT_TICKS_PER_MICROSECOND (PIT_CLOCK_FREQUENCY/1000000)
#define PIT_TICKS_PER_MILLISECOND (PIT_CLOCK_FREQUENCY/1000)
/*! Busy wait for the given time
*
* @param interval - Time to wait in PIT ticks
* @param timerChannel - PIT Channel to use (0-3)
*
* Configures:
* - Enables PIT clock
* - Enables PIT
* - Sets PIT CH1 re-load value
*
* Waits until PIT event
*/
void busyWait(int timerChannel, uint32_t interval) {
// Enable clock to PIT
SIM_SCGC6 |= SIM_SCGC6_PIT_MASK;
// Enable PIT module
PIT_MCR = PIT_MCR_FRZ_MASK;
// Set re-load value
PIT_LDVAL(timerChannel) = interval-1;
// Enable this channel without interrupts
PIT_TCTRL(timerChannel) = PIT_TCTRL_TEN_MASK;
// Clear timer flag
PIT_TFLG(timerChannel) = PIT_TFLG_TIF_MASK;
// Wait for timer event
while ((PIT_TFLG(timerChannel)&PIT_TFLG_TIF_MASK) == 0) {
__asm__("nop");
}
// Disable channel
PIT_TCTRL(timerChannel) = 0;
}
// Mask for pin to toggle
#define LED_MASK (1<<2)
int main(void) {
initialiseClock();
// Initialise PTA12
SIM_SCGC5 |= SIM_SCGC5_PORTA_MASK;
PORTA_GPCLR = PORT_GPCLR_GPWE(LED_MASK)|PORT_PCR_MUX(1);
GPIOA_PDDR |= LED_MASK;
for(;;) {
busyWait(0, 200*PIT_TICKS_PER_MILLISECOND);
GPIOA_PTOR = LED_MASK;
}
}