//Telem V0.2 22/06/16
// M. Greenman ZL1BPU

// Telemetry device for FSQ, with USB output, 9600 bps, 8 channel 12 bit.
// Added more digital inputs
  
// put your setup code here, to run once:
#define MAX_CHANNELS 6
#define MAX_SAMPLES 4
int s = 0;
uint8_t d = 0;
int adc_values[MAX_CHANNELS];
int adc_samples;

void setup() {
  pinMode(13, OUTPUT);
  
  pinMode(8, INPUT_PULLUP);
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);
  pinMode(11, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);
  pinMode(13, INPUT_PULLUP);
   
  Serial.begin(9600);
  reset_samples();
}

void loop() {
  // put your main code here, to run repeatedly:
  // read inputs, make 'd'
  d = 0;
  if (digitalRead(8) == HIGH) {d+=1;}
  if (digitalRead(9) == HIGH) {d+=2;}
  if (digitalRead(10) == HIGH) {d+=4;}
  if (digitalRead(11) == HIGH) {d+=8;}
  if (digitalRead(12) == HIGH) {d+=16;}
  if (digitalRead(13) == HIGH) {d+=32;}

  int i;
  char buffer[10];
  int average_sample;
  digitalWrite(13, HIGH);
//  delay(200);

  
  // Report current samples and clear buckets
  if (adc_samples == MAX_SAMPLES) {
        sprintf(buffer,"%03x",s);
        Serial.print(buffer);
        sprintf(buffer,"%03x",d);
        Serial.print(buffer);
        for (i=0;i<MAX_CHANNELS;i++)
    {
      average_sample = adc_values[i];
      sprintf(buffer,"%03x",average_sample);
      Serial.print(buffer);
//      Serial.print(" ");
      adc_values[i] = 0;
    }
    Serial.println("");
   adc_samples = 0;
    reset_samples();
    s = s+1;
    s = s & 4095;
    digitalWrite(13, LOW);
    delay(1000);
  }

  // Add into sample set

  for (i=0;i<MAX_CHANNELS;i++)
  {
    adc_values[i] += analogRead(i);
  }
  adc_samples++;

}

void reset_samples()
{
  // Clear buckets and reset sample count

  int i;

  adc_samples = 0;
  for (i=0;i<MAX_CHANNELS;i++)
  {
    adc_values[i] = 0;
  }
}
