]> git.piffa.net Git - sketchbook_andrea/blob - basic/analog_input/photo_6_smooth/photo_6_smooth.ino
analog cleanup
[sketchbook_andrea] / basic / analog_input / photo_6_smooth / photo_6_smooth.ino
1 /*
2   Smoothing
3  
4  Legge 10 valori dal sensore e ritorna il valore medio tra questi.
5
6  Schema: https://learn.adafruit.com/assets/460
7
8  
9  
10  */
11
12 // These constants won't change:
13 const int sensorPin = A0;    // pin that the sensor is attached to
14 const int ledPin = 11;        // pin that the LED is attached to
15
16 // variables:
17 int sensorValue = 0;         // the sensor value
18 int sensorMin = 1023;        // minimum sensor value
19 int sensorMax = 0;           // maximum sensor value
20
21
22 void setup() {
23   // turn on LED to signal the start of the calibration period:
24   pinMode(13, OUTPUT);
25   pinMode(ledPin, OUTPUT);
26   digitalWrite(13, HIGH);
27
28   // calibrate during the first five seconds 
29   while (millis() < 5000) {
30     sensorValue = analogRead(sensorPin);
31
32     // record the maximum sensor value
33     if (sensorValue > sensorMax) {
34       sensorMax = sensorValue;
35     }
36
37     // record the minimum sensor value
38     if (sensorValue < sensorMin) {
39       sensorMin = sensorValue;
40     }
41   }
42
43   // signal the end of the calibration period
44   digitalWrite(13, LOW);
45 }
46
47 void loop() {
48   // read the sensor:
49   sensorValue = smoothRead(sensorPin);
50
51   // apply the calibration to the sensor reading
52   sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
53
54   // in case the sensor value is outside the range seen during calibration
55   sensorValue = constrain(sensorValue, 0, 255);
56
57   // fade the LED using the calibrated value:
58   analogWrite(ledPin, sensorValue);
59 }
60 // Funzioni
61
62 int smoothRead(int sensorPin) {
63 //  Legge 10 valori dal sensore e ritorna il valore medio tra questi.
64   int total = 0;
65   for (int i = 0; i < 10; i++) { 
66     total = total + analogRead(sensorPin);
67     delay(2); // Pausa per assestare il senstore
68   }
69   return(total / 10); // Valore medio
70 }
71
72