unsigned long start_time;
unsigned long stop_time;
unsigned long values[1000];
const int SS_pin = 42; //tbc
const int SCK_pin = 44;
const int MISO_pin = 22;
const int MOSI_pin = 43;

String intextbuf;
String extextbuf;
byte sendValue = 0xFF;   // Value we are going to send
byte returnValue = 0;  // Where we will store the value sent by the slave



void setup() {       

  digitalWrite(SS, HIGH);  // Start with SS high
  pinMode(SS_pin, OUTPUT);
  pinMode(SCK_pin, OUTPUT);
  pinMode(MISO_pin, INPUT); //this is the avalanche pin, not implemented yet
  pinMode(MOSI_pin, OUTPUT);

  Serial.begin(115200);  
  
  REG_ADC_MR = 0x10380080;  // Free run as fast as you can
  REG_ADC_CHER = 3;   // Channels 0 and 1
  REG_ADC_CR = 2;     // Start
  Serial.print("Alive HV:");
  sendValue = 0x50;
Serial.println(sendValue);
returnValue = bitBang(sendValue); // Transmit data

}

void loop() {
  unsigned int i;
  //reads in on channel 0
    
  start_time = micros();
  for(i=0;i<1000;i++){
    //while((ADC->ADC_ISR & 0x01)==0);; // wait for conversion
    //values[i]=ADC->ADC_CDR[0];//reads ch 0 only
    while((ADC->ADC_ISR & 0x02)==0);  
    values[i]=ADC->ADC_CDR[1];//get values
  }
  stop_time = micros();

  Serial.print("Total time: ");
  Serial.println(stop_time-start_time); 
  Serial.print("Average time per conversion: ");
  Serial.println((float)(stop_time-start_time)/1000);

  Serial.println("Values: ");
  for(i=0;i<1000;i++) {
    Serial.println(values[i]);
    }
  
  delay(2000);
}


byte bitBang(byte _send)  // This function is what bitbangs the data
{

  //reception isn't implemented in this version. 
  byte _receive = 0;
   digitalWrite(SS_pin, LOW);        // SS low 
  for(int i=0; i<8; i++)  // There are 8 bits in a byte
  {
    digitalWrite(MOSI_pin, bitRead(_send, 7-i));    // Set MOSI
    //delay(1);
    digitalWrite(SCK_pin, HIGH);                  // SCK high
    //bitWrite(_receive, i, digitalRead(MISO_pin)); // Capture MISO
    digitalWrite(SCK_pin, LOW);                   // SCK low
  //digitalWrite(MOSI_pin, LOW);    // Set MOSI
    
  }
   digitalWrite(SS_pin, HIGH);       // SS high again 
 
  //return _receive;        // Return the received data
}