4 Legge 10 valori dal sensore e ritorna il valore medio tra questi.
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
14 int sensorValue = 0; // the sensor value
15 int sensorMin = 1023; // minimum sensor value
16 int sensorMax = 0; // maximum sensor value
20 // turn on LED to signal the start of the calibration period:
22 digitalWrite(13, HIGH);
24 // calibrate during the first five seconds
25 while (millis() < 5000) {
26 sensorValue = analogRead(sensorPin);
28 // record the maximum sensor value
29 if (sensorValue > sensorMax) {
30 sensorMax = sensorValue;
33 // record the minimum sensor value
34 if (sensorValue < sensorMin) {
35 sensorMin = sensorValue;
39 // signal the end of the calibration period
40 digitalWrite(13, LOW);
45 sensorValue = smoothRead(sensorPin);
47 // apply the calibration to the sensor reading
48 sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
50 // in case the sensor value is outside the range seen during calibration
51 sensorValue = constrain(sensorValue, 0, 255);
53 // fade the LED using the calibrated value:
54 analogWrite(ledPin, sensorValue);
58 int smoothRead(int sensorPin) {
59 // Legge 10 valori dal sensore e ritorna il valore medio tra questi.
61 for (int i = 0; i < 10; i++) {
62 total = total + analogRead(sensorPin);
63 delay(2); // Pausa per assestare il senstore