#include <Wire.h>

//this code sets values in the MAX5387LAUD+ via I2C.
//it then reads back those values over A1 and A2 inputs
//The ADC is set to 12 bits for the DUE
//Channels are scanned in parallel (0 to 255)
//then alternatively ascending and descending.
//Output is a CSV over serial at 9600bps.

//this test works when testing with board 2
//Note the MAX5387LAUD+ doesn't support I2C readback.


byte ADCval;
byte ADCval1;
byte ADCval2;
byte ADCval3;
byte ADCval4;
byte ADCval5;
byte ADCval6;

void setup() {
  // put your setup code here, to run once:
  pinMode(35, OUTPUT); //setup for the MAX5387 - later set to 0. signal PA0
  pinMode(36, OUTPUT);//setup for the MAX5387 - later set to 0. signal PA1
  pinMode(37, OUTPUT);//setup for the MAX5387 - later set to 0. signal PA2
  pinMode(A1, INPUT); //make sure the input pins are in high impedance mode
  pinMode(A2, INPUT);//make sure the input pins are in high impedance mode
  pinMode(11, OUTPUT);//flash the LED
  digitalWrite(35, LOW);//configure the address of the MAX5387 pot
  digitalWrite(36, LOW);//configure the address of the MAX5387 pot
  digitalWrite(37, LOW);//configure the address of the MAX5387 pot
  pinMode(5, INPUT); //set the interrupt pin for trigger as high impedance, probably not required
  
  //setup the serial for debug
  Serial.begin(9600);
  //setup the MAX5387 pot
  ADCval1 = byte(88); // <- start point for the loop
  analogReadResolution(12); 

  
attachInterrupt(digitalPinToInterrupt(5), toggleLED, RISING);

  
}


void loop() {
  Wire.begin();
  //Serial.print("MAX5387 Address ");
  //Serial.print(0x28, HEX);
  Wire.beginTransmission(byte(0x28)); // transmit to device #112
  Wire.write(byte(B00010011)); //sets the same value to both channels, if you want to tune each see max5387 datasheet
  Wire.write(ADCval1);// sets register pointer to echo #1 register (0x02)
  Wire.endTransmission();      // stop transmitting
  Serial.print("Both Channels ++ Setpoint 1:"); //note that this is manually updated by the human!
  Serial.print(ADCval1); //note that this is manually updated by the human!
  Serial.print("; Setpoint 2:"); //note that this is manually updated by the human!
  Serial.print(ADCval1); //note that this is manually updated by the human!
  Serial.print("; A1:"); 
  Serial.print(analogRead(A1));
  Serial.print("; A2:"); 
  Serial.print(analogRead(A2));
  Serial.println(";"); 
  delay(10000); //how long to wait before trying the new value
ADCval1++; //incrememnt the channel value

//digitalWrite(11, LOW); //reset the LED to low; interrupt sets it high


}

void toggleLED(){
digitalWrite(11, HIGH); //makes the LED on the board flash
digitalWrite(11, LOW); //reset the LED to low; interrupt sets it high
}
