Advertisement
Guest User

Untitled

a guest
Jan 24th, 2018
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. // As usual, we'll create constants to name the pins we're using.
  2. // This will make it easier to follow the code below.
  3. const int sensorPin = 0;
  4. const int ledPin = 9;
  5.  
  6. // We'll also set up some global variables for the light level:
  7. int lightLevel;
  8. int calibratedlightLevel; // used to store the scaled / calibrated lightLevel
  9. int maxThreshold = 0; // used for setting the "max" light level
  10. int minThreshold = 1023; // used for setting the "min" light level
  11.  
  12. void setup()
  13. {
  14. pinMode(ledPin, OUTPUT); // Set up the LED pin to be an output.
  15. Serial.begin(9600);
  16. }
  17.  
  18. void loop()
  19. {
  20. lightLevel = analogRead(sensorPin); // reads the voltage on the sensorPin
  21. Serial.print(lightLevel);
  22. //autoRange(); // autoRanges the min / max values you see in your room.
  23.  
  24. calibratedlightLevel = map(lightLevel, 0, 1023, 0, 255); // scale the lightLevel from 0 - 1023 range to 0 - 255 range.
  25. // the map() function applies a linear scale / offset.
  26. // map(inputValue, fromMin, fromMax, toMin, toMax);
  27. Serial.print("\t"); // tab character
  28. Serial.print(calibratedlightLevel); // println prints an CRLF at the end (creates a new line after)
  29.  
  30. analogWrite(ledPin, calibratedlightLevel); // set the led level based on the input lightLevel.
  31. }
  32. /******************************************************************
  33. * void autoRange()
  34. *
  35. * This function sets a minThreshold and maxThreshold value for the
  36. * light levels in your setting. Move your hand / light source / etc
  37. * so that your light sensor sees a full range of values. This will
  38. * "autoCalibrate" to your range of input values.
  39. /*****************************************************************/
  40.  
  41. void autoRange()
  42. {
  43. if (lightLevel < minThreshold) // minThreshold was initialized to 1023 -- so, if it's less, reset the threshold level.
  44. minThreshold = lightLevel;
  45.  
  46. if (lightLevel > maxThreshold) // maxThreshold was initialized to 0 -- so, if it's bigger, reset the threshold level.
  47. maxThreshold = lightLevel;
  48.  
  49. // Once we have the highest and lowest values, we can stick them
  50. // directly into the map() function.
  51. //
  52. // This function must run a few times to get a good range of bright and dark values in order to work.
  53.  
  54. lightLevel = map(lightLevel, minThreshold, maxThreshold, 0, 255);
  55. lightLevel = constrain(lightLevel, 0, 255);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement