4 Demonstrates one technique for calibrating sensor input. The
5 sensor readings during the first five seconds of the sketch
6 execution define the minimum and maximum of expected values
7 attached to the sensor pin.
9 The sensor minimum and maximum initial values may seem backwards.
10 Initially, you set the minimum high and listen for anything
11 lower, saving it as the new minimum. Likewise, you set the
12 maximum low and listen for anything higher as the new maximum.
15 * Analog sensor (potentiometer will do) attached to analog input 0
16 * LED attached from digital pin 9 to ground
23 http://arduino.cc/en/Tutorial/Calibration
25 This example code is in the public domain.
29 // These constants won't change:
30 const int sensorPin = A0; // pin that the sensor is attached to
31 const int ledPin = 9; // pin that the LED is attached to
34 int sensorValue = 0; // the sensor value
35 int sensorMin = 1023; // minimum sensor value
36 int sensorMax = 0; // maximum sensor value
40 // turn on LED to signal the start of the calibration period:
42 pinMode(ledPin, OUTPUT);
43 digitalWrite(13, HIGH);
45 // calibrate during the first five seconds
46 while (millis() < 5000) {
47 sensorValue = analogRead(sensorPin);
49 // record the maximum sensor value
50 if (sensorValue > sensorMax) {
51 sensorMax = sensorValue;
54 // record the minimum sensor value
55 if (sensorValue < sensorMin) {
56 sensorMin = sensorValue;
58 delay(5); // Let the sensor rest a bit and stabilize
61 // signal the end of the calibration period
62 digitalWrite(13, LOW);
67 sensorValue = analogRead(sensorPin);
69 // apply the calibration to the sensor reading
70 sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
72 // in case the sensor value is outside the range seen during calibration
73 sensorValue = constrain(sensorValue, 0, 255);
75 // fade the LED using the calibrated value:
76 analogWrite(ledPin, sensorValue);
80 1. Modificare lo sketch in modo che modifichi la luminosita' di un led
81 via PWM tramite il valore letto dal sensore.
82 2. Come fare per costringere la variabile dentro un intervallo stabilito?