0

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

  • see the BlinkWithoutDelay example in Arduino IDE – Juraj May 29 '21 at 09:32
  • If 1.3s is was s really 1.333... (your picture implies that it is) then this can still be done the "naive" way with simple delays. Look at the rep acting pattern of your two LEDs together and write your loop code to perform one instance of the pattern. – lurker May 29 '21 at 14:52

1 Answers1

1

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();
}

Trake Vital
  • 1,019
  • 10
  • 18