Created
January 12, 2020 22:14
-
-
Save Koepel/f7d625a6e5c0481fc4c7a9c530c643ef to your computer and use it in GitHub Desktop.
This is how I use the average
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// --------------------------------------------- | |
// averageRead.ino | |
// --------------------------------------------- | |
// License: The Unlicense, Public Domain. | |
// Author: Koepel | |
// | |
// Version 1, 2020 jan 12 | |
// First version of how I use the average. | |
// I'm not sure if this is the final version. | |
// --------------------------------------------- | |
// | |
// The average of many samples will help with a noisy signal. | |
// | |
void setup() | |
{ | |
Serial.begin( 9600); | |
} | |
void loop() | |
{ | |
Serial.print( "one sample = "); | |
int raw = analogRead( A0); | |
Serial.println( raw); | |
Serial.print( "average = "); | |
float average = averageRead( A0); | |
Serial.println( average); | |
Serial.print( "voltage = "); | |
// use 1024 and the reference voltage that you use. | |
float voltage = average / 1024.0 * 5.0; | |
Serial.println( voltage); | |
Serial.println(); | |
delay( 1000); | |
} | |
// -------------------------------------------- | |
// averageRead() | |
// -------------------------------------------- | |
// By using 'float' numbers for the average, | |
// it is possible to get more bits than | |
// the 10 or 12 bits that is returned by analogRead(). | |
// | |
// The total of the samples is not done with float, because | |
// then bits could get lost. | |
// Only at the end, the floating point calculation is done. | |
// | |
// When the voltage is calculated, use 1024, not 1023. | |
// The "half a bit" is explained here: https://www.gammon.com.au/adc | |
const int nSamples = 1000; // Usually from 5 to 10000 | |
float averageRead( int pin) | |
{ | |
unsigned long total = 0; | |
for( int i=0; i<nSamples; i++) | |
{ | |
total += (unsigned long) analogRead( pin); | |
} | |
total += nSamples / 2; // add half a bit | |
return( float( total) / float( nSamples)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment