#include <stdint.h>
#include <stdbool.h>

#include "../mcc_generated_files/pin_manager.h"
#include "userAcc.h"


void IIS_SetReg(IIS_REGS reg, uint8_t value)
{
    uint8_t tmpTx[2];
    uint8_t tmpRx[2];
    
    tmpTx[0] = IIS_WRITE | reg;
    tmpTx[1] = value;
    SPI1_CS_SetLow();
    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
    SPI1_CS_SetHigh();
    
}

uint8_t IIS_GetReg(IIS_REGS reg)
{
    uint8_t tmpTx[2];
    uint8_t tmpRx[2];
    
    tmpTx[0] = IIS_READ | reg;
    tmpTx[1] = 0;
    SPI1_CS_SetLow();
    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
    SPI1_CS_SetHigh();
    return tmpRx[2];
}


bool IIS_Init(void)
{
    uint8_t tmpTx[2];
    uint8_t tmpRx[2];
    
    uint8_t tmp;
    
//    tmpTx[0] = IIS_WRITE | IIS_CTRL_REG1;
//    tmpTx[1] = 0x9C;
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    IIS_SetReg(IIS_CTRL_REG1,0x9C);
    
    
    
    
//    tmpTx[0] = IIS_READ | IIS_CTRL_REG1;
//    tmpTx[1] = 0;
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    tmp = IIS_GetReg(IIS_CTRL_REG1);

  
//    tmpTx[0] = IIS_WRITE | IIS_FIFO_CTRL_REG;
//    tmpTx[1] = 0x00;                                //clear fifo
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    IIS_SetReg(IIS_FIFO_CTRL_REG,0x00);                 //clear FIFO
    
    
//    tmpTx[0] = IIS_WRITE | IIS_CTRL_REG5;
//    tmpTx[1] = 0x40;                                //EN fifo
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    IIS_SetReg(IIS_CTRL_REG5,0x40);                 //enable FIFO
    
    
    
//    tmpTx[0] = IIS_WRITE | IIS_FIFO_CTRL_REG;
//    tmpTx[1] = 0x98;                                //24B fifo interrupt, fifo mode stream
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    
    IIS_SetReg(IIS_FIFO_CTRL_REG,0x98);             //24B fifo interrupt, fifo mode stream
    //configured = true; 
    
    
//    tmpTx[0] = IIS_READ | IIS_FIFO_CTRL_REG;
//    tmpTx[1] = 0;
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    
    tmp = IIS_GetReg(IIS_FIFO_CTRL_REG); 
    
    
//    tmpTx[0] = IIS_WRITE | IIS_CTRL_REG3;
//    tmpTx[1] = 0x04;
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();   
    IIS_SetReg(IIS_CTRL_REG3,0x04);
    
//    tmpTx[0] = IIS_WRITE | IIS_CTRL_REG4;
//    tmpTx[1] = 0x30;
//    SPI1_CS_SetLow();
//    SPI1_Exchange8bitBuffer(tmpTx,2,tmpRx);
//    SPI1_CS_SetHigh();
    IIS_SetReg(IIS_CTRL_REG4,0x30);
    
    return true;
}