#include "config.h"
#include "dac.h"

/* Initialize DAC (AD5542) */
void dac_init(void)
{
	/* SPI2 */
	IEC2bits.SPI2IE = 0;

	SPI2CON1bits.DISSCK = 0;
	SPI2CON1bits.DISSDO = 0;
	SPI2CON1bits.MODE16 = 1;
	SPI2CON1bits.SMP = 0;
	SPI2CON1bits.CKE = 0;
	SPI2CON1bits.SSEN = 0;
	SPI2CON1bits.CKP = 1;	
	SPI2CON1bits.MSTEN = 1;
	SPI2CON1bits.SPRE = 4;
	SPI2CON1bits.PPRE = 3;

	/* There's no framed mode that does the normal
       "chip select" behavior, so control /SS2 manually */
	SPI2CON2bits.FRMEN = 0;
	LATGbits.LATG9 = 1;
	TRISGbits.TRISG9 = 0;

	SPI2STATbits.SPISIDL = 0;
	SPI2STATbits.SPIEN = 1;

	dac_write(0x0000);
}

/* Write raw 16-bit value to DAC:
   0xFFFF 4.9998v
   0x8000 0v
   0x0000 -5v
 */
void dac_write(uint16_t val)
{
	LATGbits.LATG9 = 0;
	SPI2BUF = val;
	while (!SPI2STATbits.SPIRBF)
		continue;
	(void) SPI2BUF;
	LATGbits.LATG9 = 1;
}
