/*
  0004_DenshaBekutoru ? Optocoupler Averaging Test (UNO)

  Measures average voltage on:
   - A2 -> later ATtiny85 PB3 (XTAL1, Pin 2)
   - A3 -> later ATtiny85 PB4 (XTAL2, Pin 3)

  Integration window is configurable via SAMPLE_WINDOW_MS.

  by tgohle, last edit 20260111
 
*/

const unsigned long SAMPLE_WINDOW_MS = 100;   // change here
const unsigned long SAMPLE_DELAY_US  = 500;   // delay between ADC samples

const uint8_t ADC_PIN_1 = A2;  // UNO A2  -> later ATtiny85 PB3 (XTAL1, Pin 2)
const uint8_t ADC_PIN_2 = A3;  // UNO A3  -> later ATtiny85 PB4 (XTAL2, Pin 3)

void setup() {
  Serial.begin(115200);

  pinMode(ADC_PIN_1, INPUT);
  pinMode(ADC_PIN_2, INPUT);

  Serial.println("=== DenshaBekutoru Optocoupler Average Test ===");
}

void loop() {
  unsigned long startTime = millis();

  unsigned long sum1 = 0;
  unsigned long sum2 = 0;
  unsigned long samples = 0;

  while (millis() - startTime < SAMPLE_WINDOW_MS) {
    sum1 += analogRead(ADC_PIN_1);
    sum2 += analogRead(ADC_PIN_2);
    samples++;
    delayMicroseconds(SAMPLE_DELAY_US);
  }

  float avg1 = (float)sum1 / samples;
  float avg2 = (float)sum2 / samples;

  float v1 = avg1 * (5.0 / 1023.0);
  float v2 = avg2 * (5.0 / 1023.0);

  Serial.print("A2 for PB3  XTAL1, Pin2: ");
  Serial.print(v1, 3);
  Serial.print(" V   |   ");

  Serial.print("A3 for PB4 XTAL2, Pin3: ");
  Serial.print(v2, 3);
  Serial.println(" V");

  delay(300);
}
