//-----------------------------------------------------------------------------
//
// HEADER FILES :
//#define __SENSOR_UNIVERSAL__
#include "sensors_universal.h"


void sensor_write_8bit (sensor_select_e decoder, uint8_t address, uint8_t data)
{
	SPI_setDec(decoder);
    SPI_setCs();

	SPI_master_write(address);
	
	SPI_master_write(data);
	SPI_resetAllCs();
}

uint8_t sensor_read_8bit (sensor_select_e decoder, uint8_t address)
{
	uint8_t sendframe = 0;
	
	
	SPI_setDec(decoder);
    SPI_setCs();
	sendframe  = 0x80; // set 0x80 to read
	sendframe |= address;
	SPI_master_write(sendframe);
	
	//send dummy data to generate clock
	SPI_master_write(0);

	SPI_resetAllCs();
	
	return (uint8_t)SPI_master_read();

}

uint16_t sensor_read_16bit (sensor_select_e decoder, uint8_t addressLower)
{
	uint16_t receiveframe;
	uint16_t temp;
	
	receiveframe = sensor_read_8bit(decoder, addressLower);
	temp = sensor_read_8bit(decoder, (addressLower + 1));
	receiveframe |= (temp << 8);

	
	return receiveframe;
}

float two_complement_decode(uint32_t raw_data, uint32_t mask, uint32_t lsb, float range)
{
	int bitData;		// BNR data bits including sign
	uint32_t scale;     // conversion scale
	
	bitData = (int)((raw_data >> lsb) & mask);
	
	scale = mask / 2;
	
	// if is negative number
	if (bitData > (int)scale)
	{
		bitData |= ~mask;
	}
	
	return ((float)bitData / (scale + 1) * range);
	
	
}


uint16_t sensor_read_native_16bit (sensor_select_e decoder, uint16_t address)
{
	uint16_t sendframe;
	
	SPI_setDec(decoder);
    SPI_setCs();
	//sendframe  = 0x80; // set 0x80 to read
	sendframe = address;
	SPI_master_write(sendframe);
	//send dummy data to generate clock
	SPI_master_write(0);
	
	SPI_master_write(0);
	SPI_resetAllCs();
	
	return (uint16_t)SPI_master_read();
}
