#include "MCP3550.h"
#include <stdint.h>
#include <xc.h>

void MCP3550_Init(void)
{
	MCP3550_nCS = 1;
	TRISCbits.TRISC0 = 0;		// SCK: Output
	TRISCbits.TRISC1 = 1;		// SDI: Input
	TRISCbits.TRISC2 = 0;		// CS: Output
	// SPI Init:
	APFCON0bits.SDOSEL = 1;	// SDO function is on RA4

	SSP1CON1bits.SSPM = 0x01;	// SPI Master mode, clock = FOSC/16;

	//SPI Mode 1,1: CKP=1, CKE=0
	SSP1CON1bits.CKP = 1;		// Idle state for clock is a high level
	SSP1STATbits.CKE = 0;		// Transmit occurs on transition from Idle to active clock state

	SSP1STATbits.SMP = 1;		// Input data sampled at end of data output time

	SSP1CON1bits.SSPEN = 1;	// Enables serial port and configures SCKx, SDOx, SDIx and SSx as the source of the serial port pins
}

int32_t MCP3550_GetValue(void)
{
	int32_t MCP3550_Data;

	SSP1BUF = 0xFF;
	while(!SSP1STATbits.BF);
	MCP3550_Data = SSP1BUF;

	SSP1BUF = 0xFF;
	MCP3550_Data = MCP3550_Data << 8;
	while(!SSP1STATbits.BF);
	MCP3550_Data|=SSP1BUF;

	SSP1BUF = 0xFF;
	MCP3550_Data = MCP3550_Data << 8;
	while(!SSP1STATbits.BF);
	MCP3550_Data |= SSP1BUF;

	MCP3550_nCS = 1;

	return MCP3550_Data;
}