# Moving average for ADC not working?

I came across a moving average code for my ADS1115 ADC to smooth out the noise.

When I do voltage scaling I getting zeros at my serial monitor.

I'm giving input to my ADC from an LMC6001 op-amp.

Although I'm able to read ADC values, when I do voltage scaling (voltage = (adc2 * 0.1875)/1000; which I have included in my code) I'm reading zeros on my serial monitor.

#include <Wire.h>

long int total = 0;
float average = 0.0;
float Voltage2 = 0.0;

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

void loop(void)
{
}

Serial.print("Average: "); Serial.println(average);
Serial.println(" ");
delay(1000);
}
$$$$

• adc2 looks like an integer and, if you multiply that by 0.1875 and then divide by 1000 you might shift all the relevant fractional information into the toilet never to be seen again. Shouldn't adc2 be defined as a float? I'm no expert on this BTW. Feb 16 at 15:37
• You are mixing up your floats and ints. "readings" is int, Voltage2 is float. That's going to be a problem.
– JRE
Feb 16 at 15:42
• When you do math with mixed ints and floats, you need to think really hard about the result of each step and how that result will be interpreted. It is usually safest to convert to floats, do your math, then (if needed) convert to some other numeric type.
– JRE
Feb 16 at 15:45
• You should divide by 1000.0, not 1000. 1000 is an integer and C compilers will likely interpret your code as integer divide not a float divide.
– Ben
Feb 16 at 15:47
• @Ben that would violate the C(++) type promotion rules; 1.875 is float, so the entire expression should be. Feb 16 at 17:12

Voltage2 = ((float)adc2 * 0.1875) / 1000.0;


you may end up with very small numbers (truncated do zero), assuming your ADC returns values from -32768 to 32767. Not to mention how slow the floating point operations may be (what is your micro-controller?).

Truncation to zero would happen here for small readings aprox. [-2666, 2666]:

readings[readIndex] = Voltage2;


int32_t adc2;


Try this:

#include <Wire.h>

long int total = 0;
float average = 0.0;
//float Voltage2 = 0.0;

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

void loop(void)
{
average = (float) total * 0.1875/(1000. * numReadings);

readings[readIndex] = Voltage2;
`