I'm trying to make a program that after a minute turn off or turn on an LED.
With an 8-bit timer I want to produce a delay of one second. As I want to make a 1 minute delay , I introduce this function within a for loop,to count 60 seconds.
The system clock configuration is:
internal clock frequency: 31.25 kHz
bus frequency: 1MHz
The timer setting (MTIM)
Clock source: fixed clock frecuency, is supposed to be 15625 Hz (I don't choose bus frequency because it is too large)
Prescaler: 128
Module: 123
With this configuration, the program did not work well. The delay1s () function do not produces a delay of one second, in fact, much less time and I do not understand that, because if:
fixed clock frecuency, is supposed to 15625Hz
T = 1/15625 = 64us
64us * 128 = 8,192 ms
9,192 ms * 123 = 1.007616
MC9S08QG8 :http://www.freescale.com/files/microcontrollers/doc/data_sheet/MC9S08QG8.pdf
Perhaps fixed clock frequency ( clock frecuency fixed ) is not what I thought ? Then what would ?
Does anyone know why the program did not work well?
The code is as follows :
#include <hidef.h> /* for EnableInterrupts macro */
#include "derivative.h" /* include peripheral declarations */
void MCU_init(void){ /* Device initialization function declaration */
SOPT1=0x00;
SOPT2=0x00;
ICSC1=0x04; //SETTINGS INTERNAL CLOCK SOURCE INTERNAL REFERENCE FRECUENCY=31.25kHz
ICSC2=0xC0; //SETTINGS INTERNAL CLOCK SOURCE BDIV=11 0x08
ICSTRM = *(unsigned char*)0xFFAF; /* Initialize ICSTRM register from a non volatile memory */
ICSSC = *(unsigned char*)0xFFAE; /* Initialize ICSSC register from a non volatile memory */ //frec bus =1MHz
}
void MTIM_init(){
MTIMSC=0x10;
MTIMCLK=0x17; // CLKS= Fixed frecuency clock PS=128
MTIMSC_TRST=0; //Fixed frecuency clock suposes to be (INTERNAL REFERENCE FRECUENCY/2)=15,625kHz
}
void end1s(){ // function to clear overflow flag
char aux= MTIMSC;
MTIMSC_TOF=0;
MTIMSC_TSTP=1;
}
void delay1s(){
MTIMMOD=122;
MTIMSC_TSTP=0;
while(MTIMSC_TOF==0);
end1s();
}
void main(void) {
int i=0;
PTBDD_PTBDD7=1; // lED
PTBD_PTBD7=0; // TURN OFF LED
MCU_init();
MTIM_init();
EnableInterrupts; /* enable interrupts */
for(i=0;i<60;i++)
{
delay1s();
}
PTBD_PTBD7=1; // TURN ON LED
for(i=0;i<60;i++)
{
delay1s();
}
PTBD_PTBD7=0; // TURN OFF LED
for(i=0;i<60;i++)
{
delay1s();
}
PTBD_PTBD7=1; // TURN ON LED
}