| 1 |
/* |
| 2 |
Calibration |
| 3 |
|
| 4 |
Demonstrates one technique for calibrating sensor input. The sensor readings |
| 5 |
during the first five seconds of the sketch execution define the minimum and |
| 6 |
maximum of expected values attached to the sensor pin. |
| 7 |
|
| 8 |
The sensor minimum and maximum initial values may seem backwards. Initially, |
| 9 |
you set the minimum high and listen for anything lower, saving it as the new |
| 10 |
minimum. Likewise, you set the maximum low and listen for anything higher as |
| 11 |
the new maximum. |
| 12 |
|
| 13 |
The circuit: |
| 14 |
- analog sensor (potentiometer will do) attached to analog input 0 |
| 15 |
- LED attached from digital pin 9 to ground through 220 ohm resistor |
| 16 |
|
| 17 |
created 29 Oct 2008 |
| 18 |
by David A Mellis |
| 19 |
modified 30 Aug 2011 |
| 20 |
by Tom Igoe |
| 21 |
modified 07 Apr 2017 |
| 22 |
by Zachary J. Fields |
| 23 |
|
| 24 |
This example code is in the public domain. |
| 25 |
|
| 26 |
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Calibration |
| 27 |
*/ |
| 28 |
|
| 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 |
| 32 |
|
| 33 |
// variables: |
| 34 |
int sensorValue = 0; // the sensor value |
| 35 |
int sensorMin = 1023; // minimum sensor value |
| 36 |
int sensorMax = 0; // maximum sensor value |
| 37 |
|
| 38 |
|
| 39 |
void setup() { |
| 40 |
// turn on LED to signal the start of the calibration period: |
| 41 |
pinMode(13, OUTPUT); |
| 42 |
digitalWrite(13, HIGH); |
| 43 |
|
| 44 |
// calibrate during the first five seconds |
| 45 |
while (millis() < 5000) { |
| 46 |
sensorValue = analogRead(sensorPin); |
| 47 |
|
| 48 |
// record the maximum sensor value |
| 49 |
if (sensorValue > sensorMax) { |
| 50 |
sensorMax = sensorValue; |
| 51 |
} |
| 52 |
|
| 53 |
// record the minimum sensor value |
| 54 |
if (sensorValue < sensorMin) { |
| 55 |
sensorMin = sensorValue; |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// signal the end of the calibration period |
| 60 |
digitalWrite(13, LOW); |
| 61 |
} |
| 62 |
|
| 63 |
void loop() { |
| 64 |
// read the sensor: |
| 65 |
sensorValue = analogRead(sensorPin); |
| 66 |
|
| 67 |
// in case the sensor value is outside the range seen during calibration |
| 68 |
sensorValue = constrain(sensorValue, sensorMin, sensorMax); |
| 69 |
|
| 70 |
// apply the calibration to the sensor reading |
| 71 |
sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255); |
| 72 |
|
| 73 |
// fade the LED using the calibrated value: |
| 74 |
analogWrite(ledPin, sensorValue); |
| 75 |
} |