#include <Arduino.h>

constexpr int PWM_PIN = 2;
constexpr int SENSE_PIN = 4;
int frequencyHz = 1000;
int dutyCode = 0;
char stage = 'O';
unsigned long stageAt = 0;
bool pendingMeasurement = false;

void choose(char command) {
  if (command == 'A') { frequencyHz = 1000; dutyCode = 64; }
  else if (command == 'B') { frequencyHz = 1000; dutyCode = 191; }
  else if (command == 'C') { frequencyHz = 2000; dutyCode = 191; }
  else return;
  ledcChangeFrequency(PWM_PIN, frequencyHz, 8);
  ledcWrite(PWM_PIN, dutyCode);
  stage = command;
  stageAt = millis();
  pendingMeasurement = true;
  Serial.printf("STAGE=%c configured_hz=%d duty_code=%d\n", stage, frequencyHz, dutyCode);
}

void setup() {
  Serial.begin(115200);
  pinMode(SENSE_PIN, INPUT);
  ledcAttach(PWM_PIN, frequencyHz, 8);
  ledcWrite(PWM_PIN, 0);
  Serial.println("PWM TIMING LAB READY; LED off; D2 loopback D4 and analyzer D0");
  Serial.println("Commands: A=25% at 1kHz, B=75% at 1kHz, C=75% at 2kHz");
}

void loop() {
  if (Serial.available()) choose(Serial.read());
  if (pendingMeasurement && millis() - stageAt >= 200) {
    pendingMeasurement = false;
    unsigned long highUs = pulseIn(SENSE_PIN, HIGH, 10000);
    unsigned long lowUs = pulseIn(SENSE_PIN, LOW, 10000);
    unsigned long periodUs = highUs + lowUs;
    Serial.printf("MEASURE stage=%c high_us=%lu low_us=%lu period_us=%lu duty_pct=%.1f\n",
      stage, highUs, lowUs, periodUs,
      periodUs ? 100.0 * highUs / periodUs : 0.0);
  }
  delay(5);
}
