Debian Codegraph @

examples/05.Control/WhileStatementConditional/WhileStatementConditional.ino

raw
1 /*
2 Conditionals - while statement
3
4 This example demonstrates the use of while() statements.
5
6 While the pushbutton is pressed, the sketch runs the calibration routine.
7 The sensor readings during the while loop define the minimum and maximum of
8 expected values from the photoresistor.
9
10 This is a variation on the calibrate example.
11
12 The circuit:
13 - photoresistor connected from +5V to analog in pin 0
14 - 10 kilohm resistor connected from ground to analog in pin 0
15 - LED connected from digital pin 9 to ground through 220 ohm resistor
16 - pushbutton attached from pin 2 to +5V
17 - 10 kilohm resistor attached from pin 2 to ground
18
19 created 17 Jan 2009
20 modified 30 Aug 2011
21 by Tom Igoe
22 modified 20 Jan 2017
23 by Arturo Guadalupi
24
25 This example code is in the public domain.
26
27 https://www.arduino.cc/en/Tutorial/BuiltInExamples/WhileStatementConditional
28 */
29
30
31 // These constants won't change:
32 const int sensorPin = A0; // pin that the sensor is attached to
33 const int ledPin = 9; // pin that the LED is attached to
34 const int indicatorLedPin = 13; // pin that the built-in LED is attached to
35 const int buttonPin = 2; // pin that the button is attached to
36
37
38 // These variables will change:
39 int sensorMin = 1023; // minimum sensor value
40 int sensorMax = 0; // maximum sensor value
41 int sensorValue = 0; // the sensor value
42
43
44 void setup() {
45 // set the LED pins as outputs and the switch pin as input:
46 pinMode(indicatorLedPin, OUTPUT);
47 pinMode(ledPin, OUTPUT);
48 pinMode(buttonPin, INPUT);
49 }
50
51 void loop() {
52 // while the button is pressed, take calibration readings:
53 while (digitalRead(buttonPin) == HIGH) {
54 calibrate();
55 }
56 // signal the end of the calibration period
57 digitalWrite(indicatorLedPin, LOW);
58
59 // read the sensor:
60 sensorValue = analogRead(sensorPin);
61
62 // apply the calibration to the sensor reading
63 sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
64
65 // in case the sensor value is outside the range seen during calibration
66 sensorValue = constrain(sensorValue, 0, 255);
67
68 // fade the LED using the calibrated value:
69 analogWrite(ledPin, sensorValue);
70 }
71
72 void calibrate() {
73 // turn on the indicator LED to indicate that calibration is happening:
74 digitalWrite(indicatorLedPin, HIGH);
75 // read the sensor:
76 sensorValue = analogRead(sensorPin);
77
78 // record the maximum sensor value
79 if (sensorValue > sensorMax) {
80 sensorMax = sensorValue;
81 }
82
83 // record the minimum sensor value
84 if (sensorValue < sensorMin) {
85 sensorMin = sensorValue;
86 }
87 }