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