Thursday, June 14, 2012

Smoothing

Today, I need to figure out how to smooth the code (Take the avg. of an analog input).
I hope that this will help to remove some of the bad data and get more consistent results.

The first thing I did was to use the code in the Arduino Exmples along with a light sensor.


/*How to smooth code from a light sensor
modified by Philip Leete from the Arduino Examples
tested with a light sensor wired to a 5v. circuit.
   
This code will show, with LED, how smoothing works by effecting the fade rates
of two LED lights.
*/

const int numReadings = 10;

int readings[numReadings];      // the readings from the analog input
int index = 0;                  // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average of the light values
int LED_Avg = 5;                // the LED for Avg readings is on pin 5
int LED_Real = 9;               // the LED for Real readings is on pin 9
int Light_Sensor = A0;          // the light sensor is in pin A0
int Light_Value;                // a value used to store the real light value

void setup()
{
  // initialize serial communication with computer:
  Serial.begin(9600);                
  // initialize all the readings to 0:
  for (int thisReading = 0; thisReading < numReadings; thisReading++)
    readings[thisReading] = 0;        
  pinMode(LED_Avg, OUTPUT);
  pinMode(LED_Real, OUTPUT);
}

void loop() {
  // subtract the last reading:
  total= total - readings[index];      
  // read from the sensor:
  readings[index] = analogRead(Light_Sensor);
  // add the reading to the total:
  total= total + readings[index];    
  // advance to the next position in the array:
  index = index + 1;                  

  // if we're at the end of the array...
  if (index >= numReadings)            
    // ...wrap around to the beginning
    index = 0;                        

  // calculate the average:
  average = total / numReadings;      
  // send it to the computer as ASCII digits
  Light_Value = analogRead(A0);

  analogWrite(LED_Real, Light_Value);  //this controls the fading of the LED
  analogWrite(LED_Avg, average);   //this is the fading of each LED

  Serial.print(average);
  Serial.println("  Avgerage");         //you can see how the avg will match the real value
  Serial.print(Light_Value);            //after a few moments.
  Serial.println("  Light Value");
  delay(1);                             // delay in between reads for stability          
}

-----------------------------------------

No comments:

Post a Comment