#include <Arduino.h>
#include "AD5593R.h"
#include <Wire.h>

#define m2_diode A2   // Module 2 Diode
#define dac_diode 0   // DAC diode

#define dac_0v 0        // DAC value to set 0V
#define dac_1p8v 1150   // DAC value to set 1.8V
#define dac_3p3v 2000   // DAC value to sett 3.3V

#define adc_conversion 0.00322
#define dac_conversion 0.00165

void setup() {
  Wire.begin();
  Serial.begin(115200);
  dac_setup();
}

void loop() {
  // m2_diode_discrete();
  // delay(500);

 m2_diode_sweep();
 delay(10000);
}

void m2_diode_discrete(){  
  float dac_voltage = 0.9;
  int inc = dac_voltage/dac_conversion;  
  setDACVal(dac_diode, inc);
  float resistor_voltage = (analogRead(m2_diode)*adc_conversion);
  Serial.println("Diode current in (mA), DAC Voltage (V), Diode Voltage(V)");
  Serial.print(resistor_voltage);
  Serial.print(",");
  Serial.print(dac_voltage);
  Serial.print(",");
  Serial.println(dac_voltage-resistor_voltage);  
}

void m2_diode_sweep(){
  Serial.println("Make sure that module 2 is active");
  int inc_interval = 10;
  int inc_delay = 1;
  int inc = 0;
  unsigned long prev_inc_time = 0;

  Serial.println("Diode current in (mA), DAC Voltage (V), Diode Voltage(V)");
  while(1){
    if((inc <= dac_3p3v) && (millis() - prev_inc_time > inc_delay)){
      prev_inc_time = millis();
      setDACVal(dac_diode, inc);
      float resistor_voltage = (analogRead(m2_diode)*adc_conversion);
      Serial.print(resistor_voltage);
      Serial.print(",");
      float dac_voltage = inc*dac_conversion;
      Serial.print(dac_voltage);
      Serial.print(",");
      Serial.println(dac_voltage-resistor_voltage);
      inc = inc + inc_interval;
    }
    if((inc >= dac_3p3v) && (millis() - prev_inc_time > inc_delay)){
       prev_inc_time = millis();
       setDACVal(dac_diode, 0);
       inc = 0;
       break;
    }
  }
}


void dac_setup(){
  initADAC(0x10, 1, 1);
  setDACGain(1);
  setDACpin(dac_diode);
}

void reset_dac(){
  setDACVal(dac_diode,0);
}
