Go Down

Topic: Newbie's first code: Sensor smoothing in 762 bytes (Read 652 times) previous topic - next topic

Bobnova

For starters, I hope this is the right place for this, it seemed like it was the best fit.  If not, point me in the correct direction and I'll remember for future reference.

I'm just getting into this microcontroller business, my past experience (stamp2) as annoying at best, but it seemed a lot more interesting now and the Atmega chips have the features I found lacking in the stamp2 (a timer, cheapness if I kill it, random numbers), so I gave it a go.
So far, I love it!

Anyway, I have one of the "Ambient Light Sensors" from Modern Device, it works great but throws out wild numbers from time to time, so I started working on smoothing it out.
I eventually settled on this:
Code: [Select]
int Light = 0;
int Data[10];
void setup(){}
void loop() {
 for (int Counter = 0; Counter < 10; Counter++){
   Data[Counter] = analogRead(5);
   Light = Data[0] + Data[1] + Data[2] + Data[3] + Data[4] + Data[5] + Data[6] + Data[7] + Data[8] + Data[9];
   Light = Light / 10;
   }
 

Obviously the sensor is connected to analog pin 5.
So far the only use is a simple check to see if the Light value is under a given number and turn on an LED (Yup, another "Hello world!" type thing), but eventually it's going into a light (or dark) seeking paranoid robot.

There are a couple things I'd like advice on:
1) The "Light = Data[0] + Data[1] + etc." line seems ugly, is there a better way?

2) The first time the FOR loop runs the data it spits out is dubious at best, is there any way around this?

3) It (the compiler) won't let me remove the setup section despite it being empty, why?

Groove

Quote
The "Light = Data[0] + Data[1] + etc." line seems ugly, is there a better way?

A "for" loop and "Light += Data ;".
In fact, you've already got such a loop.

Quote
The first time the FOR loop runs the data it spits out is dubious at best, is there any way around this

Then don't divide by such big numbers, or don't spit out values until the numbers have stabilised.

Quote
It (the compiler) won't let me remove the setup section despite it being empty, why?

Because "setup" is called inside the, to you invisible "main".
It has to be there, even if it is empty.
Per Arduino ad Astra

Squiggler

I used this in my code to smooth out peaks :-
Code: [Select]
//*********************************************************************
//              Averaging Read From Port
//*********************************************************************
long readAnalogAVE(int Port, int Samples) {

    long Accumulator = 0 ;

    for (int i = 0; i < Samples ; i++) {
         Accumulator = Accumulator + analogRead(Port);
    }  
    return(Accumulator / Samples) ;
}


so in your case cou could call it with :

Code: [Select]
Light = readAnalogAVE(5,10) ;

I found it was better in a function as different sensors need different number of samples!

Go Up