/*
Analog Input Demo
with minimum and maximum demo values 
plus smoothing added
*/

// These constants won't change.  They're used to give names
// to the pins used:
const int analogInPin = A2;  // Analog input pin that the flex sensor is attached to
const int analogOutPin = 3; // Analog output pin that the LED is attached to

int outputValue = 0;        // value output to the PWM (analog out)

////smoothing////
const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int readIndex = 0;              // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average
////smoothing////

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(analogOutPin, OUTPUT);
  // open serial port
  Serial.begin(9600);

  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {
  // subtract the last reading:
  total = total - readings[readIndex];

  // read the analog in value:
  readings[readIndex] = analogRead(analogInPin);
  // add the reading to the total:
  total = total + readings[readIndex];
  // advance to the next position in the array:
  readIndex = readIndex + 1;

  // if we're at the end of the array...
  if (readIndex >= numReadings) {
    // ...wrap around to the beginning:
    readIndex = 0;
  }
  average = total / numReadings;

  // map it to the range of the analog out:
  outputValue = map(average, 780, 1020, 0, 255);
 
  // change the analog out value:
  analogWrite(analogOutPin, outputValue);

  // print the results to the serial monitor:
  Serial.print("smooth sensor = ");
  Serial.print(average);
  Serial.print("\t output = ");
  Serial.println(outputValue);



  // wait 2 milliseconds before the next loop
  // for the analog-to-digital converter to settle
  // after the last reading:
  delay(20);
}
