//xsetaseta@gmail.com
//
//LTC6904 con arduino 1.8.5
//2020

/*
  I2C SDA (data line) = analog pin 4  ->CHIP SDI-pin2
  I2C SDC (clock line) = analog pin 5 ->CHIP SCK-pin3
  Resistencias de 1K a Vcc
*/

#include <Wire.h>
//#include <math.h>

#define LTC6904_ADDRESS 22  // CHIP pin ADR(4)<-VCC

/*
void setFreq(float freq, boolean compOutputOn=true) 
{
  unsigned int oct = (int) (3.322*log10(freq * 1000.0 / 1039.0));
  unsigned int dac = (int) (2048.0 - 2078.0 * pow(2, 10 + oct) / (freq * 1000.0) + 0.5);
   
  unsigned int cnf = compOutputOn ? 0 : 2;
   
  unsigned int reg = oct << 12 | dac << 2 | cnf;
   
  byte high = (reg >> 8) & 0xff;
  byte low = reg & 0xff;
   
  Wire.beginTransmission(LTC6904_ADDRESS);
  Wire.write(high);
  Wire.write(low);
  Wire.endTransmission();  
}
*/


void setFreqSETA(float freq) //HZ
{
 int z;
 long frecu;
 long mipo;
 unsigned int oct;

 
    frecu=freq;
    for(z=1;z<16;z++)
      {
        frecu/=2;
        if(frecu>1039 && frecu<2076) break;
      }

  oct =z;

  mipo=2;
  for(z=1;z<oct+10;z++)    mipo*=2;

  unsigned int dac =  2048.0 - (2078.0 *mipo) / freq;
  Serial.print(oct); Serial.print("<-oct   dac->");Serial.println(dac);
      
  unsigned int reg = oct << 12 | dac << 2 ;
   
  byte high = (reg >> 8) & 0xff;
  byte low = reg & 0xff;
   
  Wire.beginTransmission(LTC6904_ADDRESS);
  Wire.write(high);
  Wire.write(low);
  Wire.endTransmission();  
 Serial.print(high); Serial.print("<-high   low->");Serial.println(low);
}
 




void setup()
{
  Serial.begin(9600);
  Wire.begin(); // We're I2C-Bus Master

  delay(100);
  Serial.println("LTC6904");  
  setFreqSETA(10000); //set frequency to 23.0 kHz
 //Serial.print(high); Serial.print("<-high   low->");Serial.println(low);
 Serial.println("---"); 
}

 
void loop()
{
long sensorValue;
  
  sensorValue = 10*analogRead(A0);
  Serial.print("A0="); Serial.println(sensorValue); 
  
  //setFreq(sensorValue);
  setFreqSETA(256000);
  
  delay(1000);

}




