arduinoarduino-unoledtinkercad

How to make a duty cycle using 2 LEDs using arduino?


I want to make a duty cycle of 2 LEDs using Arduino in tinkercad. I have 2 LEDs 1 is red and another is green. I want both the LEDs on at the same time but a glowing delay of red led is 1second and green led is 1.3second just like the graph below and having both duty cycle 50%.

enter image description here

but I cant be able to do that I had tried with 2 blocks of if-else but it doesn't work due to its take if-else synchronously then I tried to calculate the graph and want to put it as a delay but it is not an easy solution enter image description here

I've learned about millis() is the solution but how would I use it? Please help me to solve this problem


Solution

  • Try this code:

    
    
    #define LED11_PIN 11
    #define LED12_PIN 12
    #define LED12_BLINK_RATE 1000
    #define LED11_BLINK_RATE 1300
    
    class Led
    {
      private:
      bool _ledState;
      const int _ledBlinkRate;
      double _lastStateChange;
      const int _ledPin;
      
      public:
      
      Led(int blinkRate, int ledPin) : _ledState(false),_ledBlinkRate(blinkRate), _lastStateChange(millis()), _ledPin(ledPin)
      {}
      ~Led()
      {}
      void update()
      {
        double currTime = millis();
        if((_lastStateChange + _ledBlinkRate/2) <= currTime)
        {
          _ledState = !_ledState;
          
          digitalWrite(_ledPin, _ledState);
          
          _lastStateChange = currTime;
        }
      }
      
      
    };
    
    Led led11(LED11_BLINK_RATE,LED11_PIN);
    Led led12(LED12_BLINK_RATE,LED12_PIN);
    
    void setup()
    {
      pinMode(LED12_PIN, OUTPUT);
      pinMode(LED11_PIN, OUTPUT);
    
    }
    
    void loop()
    {
        led11.update();
        led12.update();
    }