#include "ExponentialFilter.h"
#define analogInput A0
#define periodInput A1
ExponentialFilter lowPassFilter;
bool toggle;
double input;
double output;
const double amplitude = 50.0;
const double reference = 50.0;
void setup() {
Serial.begin(38400);
pinMode(LED_BUILTIN, OUTPUT);
lowPassFilter.cutoffFrequency(1.0);
}
void loop() {
int timeValue = analogRead(periodInput);
double period = map(timeValue, 0, 1023, 10, 1000) * 0.000001;
double input = SineWave(PhaseGenerator(period));
if (input > 100.0) input = 100.0;
if (input < 0.0) input = 0.0;
lowPassFilter.filter(input);
SerialPlot(lowPassFilter.input, lowPassFilter.output);
digitalWrite(LED_BUILTIN, toggle);
}
double SineWave(double period) {
double sineValue = sin(period * 1.0 * TWO_PI / 360.0 );
output = amplitude * sineValue + reference;
return output;
}
double PhaseGenerator(double delayTime) {
static double phase;
static unsigned long lastTime;
static double elapsedTime;
unsigned long currTime = micros();
unsigned long deltaTime = currTime - lastTime;
elapsedTime += deltaTime * 0.000001;
lastTime = currTime;
if (elapsedTime < delayTime) return phase;
elapsedTime = 0.0;
phase = phase + 0.1;
if (phase < 360.0) return phase;
phase = 0.0;
return phase;
}
void SerialPlot(double input, double output) {
static unsigned long startTime;
unsigned long currTime = millis();
if (currTime - startTime < 50UL) return;
toggle = !toggle;
startTime = currTime;
Serial.println(
"Input:" + String(input, 3)
+ ",Output:" + String(output, 3)
);
}