//plug the Cosmic Pi Analogue PCB in to the arduino directly, make sure you've disconnected the VBias pin and powered the SiPM's
//via an alternative power supply

//This code reads A1 and A3 in free running mode. If the values are higher than threshold, it outputs the cumulative number of events
//and the time since the last event in milliseconds. 

//the commented out part at the bottom can be used to output the actual data and is what we've been using to make some plots.
//this whole thing runs in a loop and is a long way from true realtime. 

//J. Devine 29/08/16

uint16_t bufa[5000];   // 4 buffers of 256 readings
uint16_t bufb[5000];   // 4 buffers of 256 readings
bool firstrun = 0;
int t;
int evt; //event
void setup() {
  Serial.begin(115200);
  Serial.println("Alive");
  int t = analogRead(0);
 //int evt; //events

  ADC->ADC_MR |= 0x80; // these lines set free running mode on adc 4 and adc 6 (pin A1 and A3 - see Due Pinout Diagram thread)
  ADC->ADC_CR = 2;
  ADC->ADC_CHER = 0x50; // this is (1<<7) | (1<<6) for adc 3 and adc 6
  evt=0;
}

void loop() {
  int q0 = 0, q1 = 0;
  int a1, a3;
  for (int i = 0; i < 5000; i++) {
    while ((ADC->ADC_ISR & 0x50) != 0x50); // wait for two conversions (pin A3[4]  and A1[6])
    a1 = ADC->ADC_CDR[4];            // read data on A3 pin
    a3 = ADC->ADC_CDR[6];            // read data on A1 pin
    bufa[i] = a1;
    bufb[i] = a3;
    if (bufb[i] > 920) { //software trigger
    if (bufa[i] > 920) { //software trigger
      t=millis()-t;
      Serial.print(t);Serial.print(" Trigger "); Serial.println(evt);
      evt++;
      t=millis();
    }
    }
    //q0+=a1;
    //q1+=a3;
  }
  //t = micros() - t;
  //Serial.print("5000 pairs of conversions in ");Serial.print(t);Serial.println(" micros");
  //Serial.print("A0 total:");Serial.println(q0);
  //Serial.print("A1 total:");Serial.println(q1);
  //Serial.print("A0:");Serial.println("A1:");
  /*if (firstrun) {
    for (int i = 0; i < 5000; i++) {
      if (bufb[i] > 920) { //software trigger
        if (bufa[i] > 920) { //software trigger
          //evt++;
          Serial.print(evt);Serial.print(" Time since last trigger ");Serial.print(t);Serial.println(" micros");
          //for (int j = i - 10; j < i + 40; j++) {
          //  Serial.print(j); Serial.print("; "); Serial.print(bufa[j]); Serial.print("; "); Serial.print(bufb[j]); Serial.println(";");
          //}

        }
      }
    }
  t=micros();
  }
  firstrun = 1;
*/
}


