SHARE
TWEET

Adding a Button to the 3 LEDs and Photoresistor

jmyean Apr 9th, 2019 90 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  *  Jung Min Yean
  3.  *  04/04/19
  4.  *  Learning How to Use a Photoresistor with LEDs
  5.  */
  6.  
  7.  const int LedPin1 = 9;
  8.  const int LedPin2 = 10;
  9.  const int LedPin3 = 11;
  10.  const int PhotoPin = A0;
  11.  int PhotoVal = 0;
  12.  unsigned long timeStart = 0;
  13.  int Max = 0;
  14.  int Min = 1000;
  15.  boolean currentVal;
  16.  boolean lastVal;
  17.  const int Button = 2;
  18.  
  19. void setup()
  20. {
  21.  pinMode(LedPin1, OUTPUT);
  22.  pinMode(LedPin2, OUTPUT);
  23.  pinMode(LedPin3, OUTPUT);
  24.  pinMode(PhotoPin, INPUT);
  25.  pinMode(Button, INPUT);
  26.  Serial.begin(9600);
  27.  digitalWrite(LedPin1, HIGH);
  28.  delay(100);
  29.  digitalWrite(LedPin1,LOW);
  30.   calibrate();
  31. }  
  32. boolean debounce(boolean last)
  33. {
  34.   boolean current = digitalRead(Button);
  35.   if (last != current)
  36.   {
  37.     delay(5);
  38.     current = digitalRead(Button);
  39.     Serial.println(current);
  40.   }
  41.   return current;
  42. }
  43.  
  44. void calibrate()
  45.  {
  46.   Max = 0;
  47.   Min = 1000;
  48.   analogWrite(LedPin1,200);
  49.   analogWrite(LedPin2, 0);
  50.   analogWrite(LedPin3,0);
  51.   delay(200);
  52.   analogWrite(LedPin1, 0);
  53.   analogWrite(LedPin2, 0);
  54.   analogWrite(LedPin3,0);
  55.   timeStart = millis();
  56.   while (millis()-timeStart <= 5000)
  57.   {
  58.     delay(5);
  59.     PhotoVal = analogRead(PhotoPin);
  60.     Serial.println(PhotoVal);
  61.     if(PhotoVal > Max)
  62.     {
  63.       Max = PhotoVal;
  64.     }
  65.     if(PhotoVal < Min)
  66.     {
  67.       Min = PhotoVal;
  68.     }
  69.   }
  70.   Serial.print("The Max Value is ");
  71.   Serial.println(Max);
  72.   Serial.print("The Min Value is");
  73.   Serial.println(Min);
  74.  }
  75.  
  76. void loop()
  77. {
  78.  currentVal = debounce(lastVal);
  79.  if (lastVal == LOW && currentVal == HIGH)    // Checks if the button has been pressed
  80.  {
  81.   calibrate();
  82.  }
  83.   PhotoVal = analogRead(PhotoPin);
  84.   // Serial.println(PhotoVal);
  85.   // Serial.print("      ");
  86.   int MapVal = map(PhotoVal,Min,Max,255,0);
  87.   MapVal = constrain(MapVal, 0,255);
  88.   // Serial.println(MapVal);
  89.   analogWrite(LedPin1, MapVal);
  90.   analogWrite(LedPin2, MapVal);
  91.   analogWrite(LedPin3, MapVal);
  92.   lastVal=currentVal;
  93. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top