// The purpose of this project is to provide automatic gain control for audio input so that it averages
// around a given setpoint.


#include <FastLED.h>

double error;
double inputa, outputa, inputAvg, inputAdj;
double setPoint = 100.;                                         // I want this to be our average.
double multError;


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


void loop(){

// Raw data input
  inputa = (float)inoise8(millis(),millis())/4.;                // Make a small perlin noise signal.
  inputa = inputa * (analogRead(A5)/64 + .01);                  // Multiply by the volume control. Let's not divide by 0.

  setPoint = (analogRead(A4)/4+1);                              // Here we have an adjustable setpoint.
  inputAvg = ((inputAvg * 63) + inputa) / 64;                   // Exponential smoothing over the last 32 samples.

  multError = setPoint / inputAvg;
  inputAdj = inputa * multError;



  Serial.print(setPoint); Serial.print("\t");
  Serial.print(inputa); Serial.print("\t");
  Serial.print(setPoint); Serial.print("\t");
//  Serial.print(inputAvg); Serial.print("\t");
  Serial.print(inputAdj); Serial.print("\t");

  Serial.println(" ");
  delay(5);
}