// -----------------------------------------------------------------------
//   timer.c -> timer 0 management
//   Autor:  Rodrigo Maximiano Antunes de Almeida
//          rodrigomax at unifei.edu.br
// -----------------------------------------------------------------------
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; version 2 of the License.
// 
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
// -----------------------------------------------------------------------

#include "basico.h"
#include "drvTimer.h"

static driver thisDriver;
static driver_functions this_functions[TMR_END];

char isTimerEnd(void *parameters) {
    (*(char *) parameters) = BitTst(INTCON, 2);
    return SUCCESS;
}

char waitTimer(void *parameters) {
    while (!BitTst(INTCON, 2));
    return SUCCESS;
}

//times in us
char resetTimer(void *parameters) {
    //for 8MHz, 1 ms = 2 cycles
    unsigned int cycles = ((unsigned int)parameters) * 2;
    //overflow happens with 2^15-1 = 65535 (max unsigned int)
    cycles = 65534 - cycles;
    cycles -= 14; //overhead time(experimental)
    TMR0H = (cycles >> 8); //hi byte
    TMR0L = (cycles & 0x00FF); //lo byte
    BitClr(INTCON, 2); //clean overflow flag

    return SUCCESS;
}

char startTimer(void *parameters) {
    BitSet(T0CON, 7); //timer 0 turn on
    return SUCCESS;
}

char enableTimerInt(void *parameters) {
    BitSet(INTCON, 5); //timer 0 interrupt enable
    return SUCCESS;
}

char initTimer(void *parameters) {

    thisDriver.drv_id = *(char*) parameters;
    this_functions[TMR_WAIT].func_ptr = waitTimer;
    this_functions[TMR_IS_END].func_ptr = isTimerEnd;
    this_functions[TMR_RESET].func_ptr = resetTimer;
    this_functions[TMR_START].func_ptr = startTimer;
    this_functions[TMR_INT_EN].func_ptr = enableTimerInt;

    T0CON = 0b00001000; //timer 0 without prescaler
    
    return SUCCESS;
}

driver* getTimerDriver(void) {
    //to ensure that at least the init function will be known
    thisDriver.drv_init = initTimer;
    thisDriver.func_ptr = (driver_functions*) & this_functions;
    return &thisDriver;
}
