Advertisement
Guest User

Arduino - While Loop

a guest
Jul 22nd, 2014
228
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.70 KB | None | 0 0
  1. // These constants won't change:
  2. const int sensorPin = A2;       // pin that the sensor is attached to
  3. const int ledPin = 9;           // pin that the LED is attached to
  4. const int indicatorLedPin = 13; // pin that the built-in LED is attached to
  5. const int buttonPin = 2;        // pin that the button is attached to
  6.  
  7.  
  8. // These variables will change:
  9. int sensorMin = 1023;  // minimum sensor value
  10. int sensorMax = 0;     // maximum sensor value
  11. int sensorValue = 0;         // the sensor value
  12.  
  13.  
  14. void setup() {
  15.   // set the LED pins as outputs and the switch pin as input:
  16.   pinMode(indicatorLedPin, OUTPUT);
  17.   pinMode (ledPin, OUTPUT);
  18.   pinMode (buttonPin, INPUT);
  19. }
  20.  
  21. void loop() {
  22.   // while the button is pressed, take calibration readings:
  23.   while (digitalRead(buttonPin) == HIGH) {
  24.     calibrate();
  25.   }
  26.   // signal the end of the calibration period
  27.   digitalWrite(indicatorLedPin, LOW);  
  28.  
  29.   // read the sensor:
  30.   sensorValue = analogRead(sensorPin);
  31.  
  32.   // apply the calibration to the sensor reading
  33.   sensorValue = map(sensorValue, sensorMin, sensorMax, 0, 255);
  34.  
  35.   // in case the sensor value is outside the range seen during calibration
  36.   sensorValue = constrain(sensorValue, 0, 255);
  37.  
  38.   // fade the LED using the calibrated value:
  39.   analogWrite(ledPin, sensorValue);
  40. }
  41.  
  42. void calibrate() {
  43.   // turn on the indicator LED to indicate that calibration is happening:
  44.   digitalWrite(indicatorLedPin, HIGH);
  45.   // read the sensor:
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement