/*
  Uno with Scope https://github.com/Dlloydev/Wokwi-Chip-Scope
        and https://github.com/Dlloydev/Wokwi-Chip-PWM


  Wokwi Uno https://wokwi.com/projects/390819301187622913
  Wokwi Mega: https://wokwi.com/projects/390819455604080641

  See also https://wokwi.com/projects/359331973918199809

*/

// Quadrature Generator
// https://wokwi.com/projects/403218793081155585

// Define the output pins
const int pinA = 2;
const int pinB = 3;

// Define the state machine states
enum State {STATE0, STATE1, STATE2, STATE3};
State currentState = STATE0;

// Timing variables
unsigned long previousMicros = 0;
unsigned long interval = 357; // 357 microseconds for each state
bool on = false;
void setup() {
  // Initialize the output pins
  pinMode(pinA, OUTPUT);
  pinMode(pinB, OUTPUT);

  // Initialize the pins to a known state
  digitalWrite(pinA, LOW);
  digitalWrite(pinB, LOW);
  Serial.begin(115200);
}

void readPot(void) {
  static int lastADC = -1;
  int pot = analogRead(A0);
  if (pot != lastADC) { // change detection on potentiometer
    lastADC = pot;
    //long speed = map(pot, 0, 1023, 0, 200000);
    // 
    // map quadratic per https://forum.arduino.cc/t/using-the-pow-function/258628/7
    // order of operations to fit in unsigned long: 
    long speed = pot*2000000UL/1023*pot/1023; // centiHz
    if (speed == 0) {
      on = false;
    } else {
      on = true;
      interval = 100000000.0 / speed / 4; // centiHz to us/interval
      previousMicros = micros();
    }
    Serial.print(pot);
    Serial.print(", ");
    Serial.print(speed/100.0,3); // centiHz to Hz
    Serial.print("Hz us:");
    Serial.print(interval);
    Serial.print(" Act:");
    Serial.print(pot == 0 ? 0 : 1000000.0/interval/4);
    Serial.println("Hz");
  }
}

void loop() {
  static unsigned long lastScan;
  if (millis() - lastScan > 128) {
    lastScan += 128;
    readPot();
  }
  quadGenerator();
}

void quadGenerator(){
  // Get the current time in microseconds
  unsigned long currentMicros = micros();
  // Check if the interval has passed
  if (on && currentMicros - previousMicros >= interval) {
    // Save the current time for the next interval
    //    previousMicros = currentMicros;
    previousMicros += interval;

    // Advance the state machine
    switch (currentState) {
      case STATE0:
        digitalWrite(pinA, HIGH);
        // digitalWrite(pinB, LOW);
        currentState = STATE1;
        break;

      case STATE1:
        //digitalWrite(pinA, HIGH);
        digitalWrite(pinB, HIGH);
        currentState = STATE2;
        break;

      case STATE2:
        digitalWrite(pinA, LOW);
        //digitalWrite(pinB, HIGH);
        currentState = STATE3;
        break;

      case STATE3:
        //digitalWrite(pinA, LOW);
        digitalWrite(pinB, LOW);
        currentState = STATE0;
        break;
    }
  }
}
ScopeBreakout
Loading chip...chip-pwm
Wokwi UnoScope w QuadratureGenerator https://wokwi.com/projects/403218793081155585