1
+ #include < avr/power.h>
2
+ #include < avr/io.h>
3
+
4
+ const int SAMPLES_TO_AVERAGE = 10 ;
5
+ const int SENSOR_ANALOG_PIN = 0 ;
6
+ const int INTERSAMPLE_SLEEP_TIME_MS = 20 ;
7
+ const int DELAY_BETWEEN_SAMPLE_REPORTS_MS = 2000 ;
8
+
9
+ void setup () {
10
+ power_spi_disable ();
11
+ Serial.begin (9600 );
12
+ }
13
+
14
+ void loop () {
15
+ static short samples[10 ];
16
+ static int lastSample=0 , nextSample = 0 ;
17
+ float mean, stdDev;
18
+ int msDelayed = 0 ;
19
+ // Sample at a high rate until we get a reasonably stable reading
20
+ // to report.
21
+ do {
22
+ // Capture the next sample using the samples array as a
23
+ // ring buffer.
24
+ if (nextSample == SAMPLES_TO_AVERAGE)
25
+ nextSample = 0 ;
26
+ samples[nextSample++] = analogRead (SENSOR_ANALOG_PIN);
27
+ // Grab the stats from the samples - a mean to report
28
+ // and a standard deviation to decide whether the rate
29
+ // of change and/or size of error is too great to bother
30
+ // reporting this result.
31
+ calcSampleStats (samples, mean, stdDev);
32
+ delay (INTERSAMPLE_SLEEP_TIME_MS);
33
+ // Intersample sleep time can overflow, but if it does
34
+ // things are busted enough that we have worse problems.
35
+ msDelayed += INTERSAMPLE_SLEEP_TIME_MS;
36
+ } while (!reportResult (mean, stdDev));
37
+ // Having got a good reading, go to sleep until
38
+ // we're ready to take the next one.
39
+
40
+ delay (36000 ); // TEN MINUTE delay
41
+ }
42
+
43
+ void calcSampleStats (const short * const samples, float & sampleMean, float & stdDev) {
44
+ int sampleSum = 0 ;
45
+ // Find the mean of the humidities
46
+ for (int i = 0 ; i < SAMPLES_TO_AVERAGE; i++) {
47
+ sampleSum = sampleSum + samples[i];
48
+ }
49
+ sampleMean = float (sampleSum)/10 ;
50
+ // Then the sum of the squares of the differences
51
+ // between each sample and the mean:
52
+ float sqDevSum = 0 ;
53
+ for (int i = 0 ; i < SAMPLES_TO_AVERAGE; i++) {
54
+ sqDevSum += pow (sampleMean - float (samples[i]), 2 );
55
+ }
56
+ // Find the square root of the above divided by the
57
+ // number of samples:
58
+ stdDev = sqrt (sqDevSum/SAMPLES_TO_AVERAGE);
59
+ }
60
+
61
+ boolean reportResult (float & mean, float & stdDev) {
62
+ static boolean lastResultGood = true ;
63
+ if (stdDev < 5 ) {
64
+ Serial.print (" \n Mean:" );
65
+ Serial.print (mean);
66
+ Serial.print (" , Std. Dev: " );
67
+ Serial.print (stdDev);
68
+ lastResultGood = true ;
69
+ } else {
70
+ if (lastResultGood) {
71
+ Serial.print (" \n Waiting for value to stabilize: " );
72
+ } else {
73
+ Serial.print (" ." );
74
+ }
75
+ lastResultGood = false ;
76
+ }
77
+ return lastResultGood;
78
+ }
0 commit comments