Wednesday, 29 July 2015

Unusual harmonic data reading from phototransistor in a simple arduino setup


I have a very simple circuit for detecting ambient light readings with an arduino, but I'm noticing a sinusoidal pattern to the readings I'm getting that are hard to pin down the source of. How do I eliminate the noise so I get a more or less constant reading?


My circuit is:


schematic


simulate this circuit – Schematic created using CircuitLab


My code is simply:


int analogPin = 0;     


int val = 0;

void setup()
{
Serial.begin(9600);
}

void loop()
{

val = analogRead(analogPin);
Serial.println(val);
delay(33);
}

I graphed the results and it looks like this, oscilating between the values of 175 and 110, on a scale that goes from 0 to 1000 normally:


enter image description here


The period is about 8.5 seconds between crests, with downward blips about once every 1.4 seconds. Nothing in the light around me would explain this obviously... what's going on? How do I get more consistent values?


Solution


I took random samples over the course of the sample period and that seemed to help out a lot.



int analogPin = 0;     // potentiometer wiper (middle terminal) connected to 
analog pin 3
// outside leads to ground and +5V
int val = 0; // variable to store the value read
int maxwait = 200;
int varwait = 2000;

void setup()
{
Serial.begin(9600); // setup serial

}

void loop()
{
long sum = 0;
int count = 0;
int endTime = millis() + maxwait;
while(millis() < endTime){
sum += analogRead(analogPin);
count++;

delayMicroseconds(rand() % varwait);
}
Serial.println(sum / count);
}

Answer



The reason is probably an aliasing effect of your sampling frequency with the line frequency that powers some fluorescent or LED lights.


E.g. if the sampling frequency is alsmost a multiple of 50 or 60Hz (depending on your electrical power system), but not exactly: if the difference between sampling frequency and multiple of power line frequency is just 1/8.5s = 0.118 Hz you get this sinusoidal response.


See following image taken from Sampling sinusoidal functions: enter image description here


The red sinusoidal line represents the variation of light intensisty by line frequency (50/60Hz).
The blue sinusoidal line represents your output.

The black dots represent your sampling events (it works also if they are even more spread as shown in the image; i.e. e.g. sampling in every n-th period).


No comments:

Post a Comment

arduino - Can I use TI&#39;s cc2541 BLE as micro controller to perform operations/ processing instead of ATmega328P AU to save cost?

I am using arduino pro mini (which contains Atmega328p AU ) along with cc2541(HM-10) to process and transfer data over BLE to smartphone. I...