/* 
 * File:   sound.c
 * Author: Claire Chen and Mark Zhao
 *
 * Created on November 3, 2016, 2:13 PM
 */

#include "sound.h"

//=========================DAC Functions=====================================

/*
 * Initialize DAC using SPI channel 2
 */
void DAC_init(void){
  /* Steps:
   *    1. Set up SS as digital output.
   *    2. Map SDO to physical pin.
   *    3. Configure SPI control and clock with either of a or b:
   *        a. OpenSPIx(config1, config2) and SpiChnSetBrg(spi_channel, spi_brg)
   *        b. SpiChnOpen(spi_channel, config, spi_divider)
   */
    
  // Set up CS as digital output to RPB4 
  mPORTBSetPinsDigitalOut(BIT_4); // Make CS an output 
  mPORTBSetBits(BIT_4); // Clear CS
  
  // Map SDO2 to physical pin 
  PPSOutput(2, RPA1, SDO1);

  // Configure SPI control and clock
  OpenSPI1(SPI_MODE16_ON | SPI_CKE_ON | MASTER_ENABLE_ON, SPI_ENABLE);
  // Update SPI channel 1 baud rate generator register   
  SpiChnSetBrg(spi_channel, spi_brg);
}

/*
 * Write to channel A of DAC to play digit tones
 */
void DAC_write(uint16_t DAC_data){
  mPORTBClearBits(BIT_4); // Set CS to low prior to writing data, select MCP4822 DAC
  //while (TxBufFullSPI2()); // Ensure that transmit buffer is free before writing
  WriteSPI1(DAC_data);
  while (SPI1STATbits.SPIBUSY); // Wait for end of transaction
  mPORTBSetBits(BIT_4); // Set CS to high to end transaction
}

/*
 * Initialize and configure timer 2 for DDS
 * for DDS, period should be pb_clock/Fs
 */

void config_sound_timer(void){
  // Set up timer2 on,  interrupts, internal clock, preeescalawr 1, period
    OpenTimer2(T2_ON | T2_SOURCE_INT | T2_PS_1_1, pb_clock/Fs);
    // set up the timer interrupt with a priority of 2
    ConfigIntTimer2(T2_INT_ON | T2_INT_PRIOR_2);
    mT2ClearIntFlag(); // and clear the interrupt flag
}


