
#include "ptrans.h"

void puerto_serial_event() interrupt 4 using 1;
unsigned char relojSerial();
char enviar_comando(unsigned char, unsigned char, unsigned char[3]);


void init_pto(){
    TI=0;
    SBUF=CMD_CANCELAR;
}

void puerto_serial_event() interrupt 4 using 1{
	if(RI == 1){	                // if reception occur 
        RI = 0; 			        // clear reception flag for next reception 
        if(SBUF==CMD_ACK){          
            ROk=1;
        }
	}
    if(TI==1){                      //if transmition occurs
        TI=0;                       //clears TI
        ROk=0;
    }
}


// send command
// inputs:
//          direccion   =   slave address
//          comando     =   command byte to the slave (data)
//          parametros  =   data bytes
//
// return:
//          0           =   the transmition was ok
//          1           =   there were erros in the transmition
char enviar_comando(unsigned char direccion, unsigned char comando, unsigned char parametros[3]){
    unsigned char i;
    TI=0;
    SBUF=CMD_INICIAR;   // sends start command
    SBUF=direccion;     // sends the slave address
    if(relojSerial()==0){
        ROk=0;
        SBUF=CMD_CANCELAR;
        return 1;
    }
    SBUF=comando;       //  sends a command byte
    if(relojSerial()==0){
        ROk=0;
        SBUF=CMD_CANCELAR;
        return 1;
    }
    for(i=0;i<3;i++){
        SBUF=parametros[i]; // sends the 3 data bytes
        if(relojSerial()==0){
            ROk=0;
            SBUF=CMD_CANCELAR;
            return 1;
        }
    }
    SBUF=CMD_FINALIZAR;     // sends the finish command 
    return 0;
}

unsigned char relojSerial(){    // wait 5ms aprox for the ack
    unsigned char i,j,sw;
    sw=0;
    i=0;
    j=0;
    while((sw==0)&&(i<10)){
        sw=ROk;     // if ROk=1 the ack arrives
        if(j>181){
            j=0;
            i++;
        }
        else{
            j++;
        }
    }
    return sw;  // if 0 no ack arrives
}
