#include "delay.h"
#include <xc.h> //XC32 prekladac

void delayMs(unsigned int ms) {
    
    if(ms == 0) { //omezeni 1 - 500 ms
        ms = 1;
    }
    
    else if(ms > 500) {
        ms = 500;
    }
    
    //timer 5
    T5CONbits.ON = 0; //vypnout
    TMR5 = 0; //nulovat
    IFS0bits.T5IF = 0; //nulovat flag
    T5CONbits.TCKPS2 = 0; //prescaler /8 => 8 / 1MHz = 8us
    T5CONbits.TCKPS1 = 1;
    T5CONbits.TCKPS0 = 1;
    PR5 = ms * 125; //cca 1 - 500 ms
    IEC0bits.T5IE = 0; //zakazat preruseni
    T5CONbits.ON = 1; //spustit
    
    while(!IFS0bits.T5IF); //pockat
    
    T5CONbits.ON = 0; //vypnout
    IFS0bits.T5IF = 0; //nulovat flag
}

void delayUs(unsigned int us) {
    if(us < 20) { //omezeni 20 - 65000 us
        us = 20;
    }
    
    else if(us > 65000) {
        us = 65000;
    }
        
    //timer 5
    T5CONbits.ON = 0; //vypnout
    TMR5 = 0; //nulovat
    IFS0bits.T5IF = 0; //nulovat flag
    T5CONbits.TCKPS2 = 0; //prescaler /1 => 1 / 1MHz = 1us
    T5CONbits.TCKPS1 = 0;
    T5CONbits.TCKPS0 = 0;
    PR5 = us; //cca 10 - 65 000 us
    IEC0bits.T5IE = 0; //zakazat preruseni
    T5CONbits.ON = 1; //spustit
    
    while(!IFS0bits.T5IF); //pockat
    
    T5CONbits.ON = 0; //vypnout
    IFS0bits.T5IF = 0; //nulovat flag
}