Hello,
For a 30 second delay, the software loop method would be inappropriate. You might base your timing on either the TPM module or the MTIM module. The idea is to generate an interrupt at regular intervals, and use a global variable to count the number of interrupts, as has already been suggested.
Here are some code snippets to demonstrate this. For delays of tens of seconds I might suggest a periodic interrupt period of, say 10 milliseconds. I will also assume the use of the MTIM module for this purpose. The clock source for this module could be either the bus clock or the fixed frequency clock. However, I will assume use of the fixed frequency clock.
The fixed frequency clock is one half the reference frequency. Assuming that FEI mode is used, and assuming the factory trimmed reference frequency of 31.25 kHz, the fixed frequency clock will be 15.625 kHz, or 64 us clock period. A total of 156 clock periods will give a delay of 9.98 milliseconds, which is assumed to be sufficiently accurate for this timing purpose. The 156 clock periods would be achieved with MTIMMOD = 155; and prescale division by 1.
The required action upon timeout of the 30 second delay might be handled using one of two methods - processing within the ISR function itself, or using frequent polling of the timeout status within the main loop. The polling method would be adopted if the timeout action were lengthy. For this example, I have assumed the polling method.
In addition to the ISR function, other functions will be needed to initialise the MTIM module, to start each timeout period, and the polling function to test whether delay timeout has occurred. There are many possible variations - this is just one example.
// Global variables:volatile word delay_count = 0; // Counter for MTIM overflowsvolatile byte tflag = 0; // Timeout flag// MTIM initialisation:void MTIM_init( void){ MTIMSC = 0x30; // Clear & stop timer MTIMMOD = 155; MTIMCLK = 0x10; // Fixed freq clock, prescale 1 MTIMSC_TOF = 0; // Ensure overflow flag is clear}
// Set timeout delay - 1 second increment, 255 seconds maximumvoid set_delay( byte delay){ delay_count = (word)delay * 100; MTIMSC = 0x60; // Start timer, enable interrupt MTIMSC_TOF = 0; // Ensure overflow flag is clear tflag = 0; // Clear timeout flag}// Polling function to be frequently called - test for delay timeoutvoid test_timeout( void){ if (tflag) { // Test for timeout tflag = 0; // Clear timeout flag // Code for delay timeout action here }}
// MTIM ISR function:interrupt void MTIM_ISR( void){ MTIMSC_TOF = 0; // Clear overflow flag if (delay_count) { delay_count--; // Decrement counter if non-zero if (delay_count == 0) { // Test for timeout occurred tflag = 1; // Set timeout flag MTIMSC = 0x70; // Clear and stop timer } }}
A disclaimer - this specific code has not been tested. You will need to do the testing and debug as might be required.
Regards,
Mac