LED On & Off Code


 const int LED = 9; //Led in port 9
    const int BUTTON = 7; //Button input port 7
    
    int val = 0; //0 is depressed, 1 is pressed
    
    int old_val = 0; // stores the previous value of "val"
    int state = 0; //light is off when 0, on at 1
    
    int brightness = 128; //Stores brightness value
    unsigned long startTime = 0; //When did press start?
    
    void setup() {
      // put your setup code here, to run once:
      pinMode(LED, OUTPUT);
      pinMode(BUTTON, INPUT);
    }
    
    void loop() {
      // put your main code here, to run repeatedly: 
      val = digitalRead(BUTTON);
      
      //check if there was a transition
      if ((val == HIGH) && (old_val == LOW)){
        
       state = 1 - state; //change the state from off to on
                        //or vice-versa
                        
       startTime = millis(); // millis returns time since last reset
                             // in milliseconds
       
       delay(10);
        
      }
      
      //check whether the button is being held down
      
      if ((val == HIGH) && (old_val = HIGH)) {
        
        //if the button is helf for more than 500ms
        if ((state == 1) && ((millis() - startTime) >500)) {
          
          brightness++;
          delay(10);
          
          if (brightness > 255) {
            
            brightness = 0;
            
          }
          
        }
      
    }
    
    old_val = val;
    
    if (state == 1){
      analogWrite(LED, brightness);
      
    } else {
      analogWrite(LED,0);
    }
    }

No comments:

Post a Comment