#include "set_codec.h"
#include "set_settings.h"

// declaration of codec, an instance of Codec 
               WM8960 codec;


 //Find SampleRate settings in WM8960 Tech Manual - Tables 40, 41, and 45
 //Master Clock is 24MHz from hardware oscillator on Sparkfun Codec board

 void setWM8960SampleRate()
 {
   // CLOCK STUFF, These settings will get you 44.1KHz or 32KHz sample rate, 
   // and class-D Speaker Amp freq at 705.6kHz

  codec.enablePLL(); // PhaseLockLoop
  codec.setPLLPRESCALE(WM8960_PLLPRESCALE_DIV_2);
  codec.setSMD(WM8960_PLL_MODE_FRACTIONAL);
  codec.setCLKSEL(WM8960_CLKSEL_PLL);
  codec.setSYSCLKDIV(WM8960_SYSCLK_DIV_BY_2);
  codec.setBCLKDIV(4);
  codec.setDCLKDIV(WM8960_DCLKDIV_16);

  if(SAMPLE_RATE == 41000){  // From set_settings.h
      codec.setPLLN(7);
      codec.setPLLK(0x86, 0xC2, 0x26); // PLLK=86C226h, SYSCLK=11.2896MHz
      codec.setADCDIV(0); // default = 1
      codec.setDACDIV(0); // default = 1
  }
  else if(SAMPLE_RATE == 32000){  // From set_settings.h
      codec.setPLLN(8);
      codec.setPLLK(0x31, 0x26, 0xE8); // PLLK=3126E8, SYSCLK=12.288MHz
      codec.setADCDIV(1); // 1.5
      codec.setDACDIV(1); // 1.5
  }
  codec.setWL(WM8960_WL_16BIT);

 }  // End of setWM8960SampleRate()       



 //Some functions built to load Codec registers, most are set in Codec.init()
 //From Example_09_I2S_Bluetooth.ino for DAC out only, no ADC

 void codec_sets()         //to be executed in main.cpp
 {  
     //Example_09 I2S DAC only, no ADC
     // General setup needed
  codec.enableVREF();
  codec.enableVMID();

  // Connect from DAC outputs to output mixer
  codec.enableLD2LO();
  codec.enableRD2RO();

  // Set gainstage between booster mixer and output mixer
  // For this loopback example, we are going to keep these as low as they go
  codec.setLB2LOVOL(WM8960_OUTPUT_MIXER_GAIN_NEG_21DB); 
  codec.setRB2ROVOL(WM8960_OUTPUT_MIXER_GAIN_NEG_21DB);

  // Enable output mixers
  codec.enableLOMIX();
  codec.enableROMIX();

  setWM8960SampleRate();  // Defined above

  codec.enablePeripheralMode();
  //codec.enableMasterMode();
  //codec.setALRCGPIO(); // Note, should not be changed while ADC is enabled.

  // Enable ADCs and DACs
  codec.disableAdcLeft();
  codec.disableAdcRight();
  codec.enableDacLeft();
  codec.enableDacRight();
  codec.disableDacMute();

  //codec.enableLoopBack(); // Loopback sends ADC data directly into DAC
  codec.disableLoopBack();

  // Default is "soft mute" on, so we must disable mute to make channels active
  codec.disableDacMute(); 

  codec.enableHeadphones();
  codec.enableOUT3MIX(); // Provides VMID as buffer for headphone ground

  Serial.println("Volume set to +0dB");
  codec.setHeadphoneVolumeDB(0.00);
  codec.enableSpeakers();
  codec.setSpeakerVolumeDB(0.00);

  
  Serial.println("Codec Setup complete. Listen on Headphone outputs.");
  
 };
