// https://wokwi.com/projects/409325290405496833
// custom-chip-RCfilter.ino
// An implementation of an RC filter in a Wokwi custom chip
//
// See also 
// https://wokwi.com/projects/411487509400518657 -- example using github dependency
// from https://github.com/drf5n/Wokwi-Chip-RCfilter
// 
// See https://docs.wokwi.com/chips-api for API
//
// SPDX-License-Identifier: MIT
// Copyright (C) 2024 David Forrest

// Connections:
// 0-5V pot wiper attached to A0
// pin 3 PWM out to RC filter IN
// RC filter custom chip OUT to A3

const int PotPin = A0;
const int OutPin = 3;
const int LCFilterPin = A2;
long periodUs = 1000;

const int UsePWM = false;
uint8_t outState = LOW;
uint32_t now;

void setup() {
  Serial.begin(115200);
  pinMode(A2, INPUT);
  pinMode(3, OUTPUT);
  Serial.print(
    F("Wokwi Simulated LC filter \n"
      "Adjust the pot to change the frequency of pin 3\n"
      "Observe the LC filtered voltage on A3\n"
      "Adjust the R and C parameters on the R-C filter custom chip\n"
      "(Fiddle with the VERBOSE in analog-rcfilter.chop.c)\n"
      "See also https://wokwi.com/projects/409338384750028801\n"
     ));
}

void loop() {
  UI();
  if (!UsePWM) {
    now = micros();
    uint32_t interval = periodUs / 2;
    static uint32_t last = -interval;

    if (now - last >= interval) {
      last += interval;
      digitalWrite(OutPin, digitalRead(OutPin) == HIGH ? LOW : HIGH);
    }
  }
  // report();
}


void UI() {
  uint32_t now = millis();
  static int lastPot = -1;
  int potVal = analogRead(PotPin);
  if (potVal != lastPot) {
    lastPot = potVal;
    if (UsePWM) {
      analogWrite(OutPin, potVal / 4);
    } else { // pot controls frequency
      float frequency = pow(1000, (0.0 + potVal) / (1023));
      periodUs = 1000000 / frequency;
      Serial.print(frequency);
      Serial.print("Hz, ");
      Serial.print(periodUs);
      Serial.println("us");
    }
  }

}

void report() {
  uint32_t interval = 770000;
  static uint32_t last = -interval;
  if (now - last >= interval) {
    last += interval;
    Serial.print("Analog: ");
    Serial.println(analogRead(LCFilterPin));
  }
}
R-C FilterBreakout
Loading chip...chip-scope