
#define CS 9 //Selection Pin
#define DATA 10  //data from A/D
#define SCLK  11  //Clock
#define CONVST  12  //Start conversion

int readvalue;
unsigned long PrevTime;
unsigned long CurrtTime;
unsigned long ElapTime;


//   function to read data from ADC
int read_adc(){
  int tempbit = 0;
  int adcvalue = 0;

  digitalWrite(CS,LOW); //Select adc
  digitalWrite(CONVST,LOW); //Start conversion
  digitalWrite(CONVST,HIGH); //prevent power-down mode
  digitalWrite(CS, HIGH); // without busy indicator mode
  delayMicroseconds(1); // wait for conversion (650 ns)


  //read bits from adc
  digitalWrite(CS,LOW); //Start feeding data

  for (int i=11; i>=0; i--){
    adcvalue+=digitalRead(DATA)<<i;
    //cycle clock
    digitalWrite(SCLK,HIGH);
    digitalWrite(SCLK,LOW);
  }

  digitalWrite(CS, HIGH); // data read, back to default

  return adcvalue;
}


//   function to reset ADC (init)
void reset_adc(){
  
/*
To issue a software reset,
1. Start a conversion.
2. Read back the conversion result by pulling CS low after the
conversion is complete.
3. Between the second and eighth SCLK cycles, pull CS high
to short cycle the read operation.
4. At the end of the next conversion, the software reset is
executed.
*/

  digitalWrite(CS,LOW); //Select adc
  digitalWrite(CONVST,LOW); //Start conversion
  digitalWrite(CONVST,HIGH); //prevent power-down mode
  digitalWrite(CS, HIGH); // without busy indicator mode
  delayMicroseconds(1); // wait for conversion (650 ns)


  //read bits from adc
  digitalWrite(CS,LOW); //Start feeding data

  for (int i=8; i>=0; i--){
    // short cycle clock 
    digitalWrite(SCLK,HIGH);
    digitalWrite(SCLK,LOW);
  }

  digitalWrite(CS, HIGH); // short cycle end
  read_adc(); // full conversion to finish reset

  
}

void setup() {

  pinMode(13, OUTPUT); // initialize digital pin 13 as an output - LED.
  digitalWrite(13, HIGH);   // turn the LED on (HIGH is the voltage level)

  pinMode(CS, OUTPUT);
  pinMode(DATA, INPUT);
  pinMode(SCLK, OUTPUT);
  pinMode(CONVST, OUTPUT);

  //ADC init
  digitalWrite(CONVST, HIGH); // adc starts conversion on falling edge
  digitalWrite(CS, HIGH);
  digitalWrite(SCLK, LOW);
  reset_adc();

  // initialize serial communications at 115200 bps:
  Serial.begin(115200); 

  PrevTime = 0; //set time to 0
}


//   main loop
void loop() {

  // measure loop execution time for timestamp
  CurrtTime = micros();
  ElapTime = CurrtTime - PrevTime;
  PrevTime = CurrtTime;

  if (ElapTime > 10000) { 
    ElapTime -= 4294967294; // overflow occured, fix
  } else {
    Serial.print(read_adc());
    Serial.print(",");
    Serial.print(ElapTime);
    Serial.print('\n');
  }
    
                   
}



