Help blink leds with Millis() function

I want to blink two LEDs with Millis() in this manner::
Led1 is ON for few secs. Then OFF for few secs.

Led2 is ON for few secs . Then OFF for few secs.

Again Led1 is ON for few secs. Then OFF for few secs. and so on....

Machine_IMP1.ino (3.92 KB)

See Blink Multiple LED Without Delay

I want alternatively on and off with duration
For each on and each off.
Your suggested code alternates
But abruptly and with variable durations
But I wan everything symmetric here....

Another approach..

#include "blinker.h"
#include "idlers.h"


blinker  firstLED(13,2000,8000);
blinker  secondLED(16,2000,8000);
timeObj  midTimer(4000);

void setup() {
   
   firstLED.setOnOff(true);   // Fire up your first LED
   while(!midTimer.ding()) idle();   // Wait for it to finish it's blink cycle..
   secondLED.setOnOff(true);  // Fire up your second LED.
}

void loop() {
   idle();   // This runs your LEDs in the background. And anything else that's in the background as well.
   // Do whatever else you want. Just NOT delay();
}

You'll need the LC_baseTools library to make this work.

-jim lee

Almost any functionality can be programmed in idfferent ways. Each way has its own combination of pro's and con's.

The ezOutput-library replaces small pieces of code with selfexplaining names.
This means the user has to look inside the library to understand what the code does.
Well this is just one way of creating functionality and to learn what code does.

It is well suited for blinking LEDs. Whenever the user wants to do something with timing that is different from switching an IO-Pin you are stumped the ezOutput-library. You still will have to learn how to do the timing in this other cases.

I want to add a second way. This version has some specialties with its own pro's and con's
selfexplaining names, not a class of code but a predefined function that can be copied & pasted
specialtiy: uses a paremeter called by refrence (the "&"-symbol in the functions definition which is kind of a con)

still pretty compact, but offers a bit more direct inside what is the code doing.

The demo-code shows the non-blocking character through using the serial interface. you only need your arduino-board and that's all to make the democode run.

For blinking LEDs you still need to use the basic commands how you setup an IO-Pin as output and how to switch this IO-pin HIGH and LOW. Which is a con and a pro at the same time:
con: you need time to learn basic commands. pro: you do learn how basic commands work.

So here is the demo-code that shows the functionality with serial output.

unsigned long DemoTimerA = 0; // variables that are used to store timeInformation
unsigned long DemoTimerB = 0; 
unsigned long DemoTimerC = 0; 
unsigned long DoDelayTimer = 0; 


boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
  if ( millis() - expireTime >= TimePeriod )
  {
    expireTime += TimePeriod;  // set new expireTime
    return true;               // more time than (last check + TimePeriod) has elapsed since last 
  } 
  else return false;           // not expired
}


void setup() 
{
  Serial.begin(115200);
  Serial.println("Program started");
}


void loop() 
{
  if (  TimePeriodIsOver(DemoTimerA,1000) )
    {
      Serial.println(" TimerA overDue");
    }
       
  if (  TimePeriodIsOver(DemoTimerB,2000) )
    {
      Serial.println("                TimerB overDue");
    }

  if (  TimePeriodIsOver(DemoTimerC,3000) )
    {
      Serial.println("                               TimerC overDue");
    }

  if (  TimePeriodIsOver(DoDelayTimer,20000) )
    {
      Serial.println("every 20 seconds execute delay(3500)... to make all other timers overdue");
      delay(3500);
    }
    
}

For making LEDs blink this code has to be modified with using the commands

pinMode()
digitalWrite()

best regards Stefan

74younus:
I want alternatively on and off with duration
For each on and each off.
Your suggested code alternates
But abruptly and with variable durations
But I wan everything symmetric here....

Aha. So I want to ask a few things back to get a very precise picture:
Do you mean whenever LED A is on LED B is off and vice versa?
or with example numbers: do you mean LED A is ON for let's say 3 seconds then OFF for 5 seconds - repeat
at the same time LED B is ON for 4 seconds and is OFF for 2 seconds - repeat
The numbers are just example-numbers.
Will your project be finished if your code is doing this or will you expand the code to much more things over time?
best regards Stefan

Thankyou for your reply but as you have show varying durations I do not need them I need same ON time and OFF time but in a proper manner say when first is ON second is OFF and stays OFF . Then first is now OFF and second is also OFF .this is for one part of program.

Now second turns ON and first is still OFF and stays OFF now Second tuns OFF while first is still OFF and time comes again for first to be ON and second is OFF so on and so forth.

74younus:
Thankyou for your reply but as you have show varying durations I do not need them I need same ON time and OFF time but in a proper manner say when first is ON second is OFF and stays OFF . Then first is now OFF and second is also OFF .this is for one part of program.

Now second turns ON and first is still OFF and stays OFF now Second tuns OFF while first is still OFF and time comes again for first to be ON and second is OFF so on and so forth.

Sorry but you’re making very little sense.
Perhaps draw a graph of output vs time for both LEDs?

74younus - please do us all a favour and follow the instructions on posting code in Read this before posting a programming question

OK I have an attachment please see it.
Please suggest some code.

74younus:
OK I have an attachment please see it.
Please suggest some code.

This is more what I had in mind when I suggest posting your code

const int led1 = 10;
const int led2 = 11;
const int led3 = 12;
const int led4 =  13;   // the pin numbers for the LEDs

int Reset = 4;
int Received = 0;

const int led_Interval = 2300; // number of millisecs Motor is ON
const int blinkDuration = 2500; // number of millisecs that Motor is OFF
const int  led_Interval2 = 2100;
const int blinkDuration2 = 2700;
const int  led_Interval3 = 1800;
const int blinkDuration3 = 3000;
//------- VARIABLES (will change)

byte led1_State = LOW;             // used to record whether the LEDs are on or off
byte led2_State = HIGH;           //   LOW = off
byte led3_State = HIGH;          //
byte led4_State = HIGH;


//------- Time
unsigned long currentMillis = 0;    // stores the value of millis() in each iteration of loop()
unsigned long previousled1Millis = 0;   // will store last time the LED was updated
unsigned long previousled2Millis = 0;
unsigned long previousled3Millis = 10;




void setup()
{
  Serial.begin(9600);
  //Serial.println("Starting SeveralThingsAtTheSameTimeRev1.ino");  // so we know what sketch is running
  //-------  set the Led pins as output:
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  digitalWrite(led4, LOW);
  digitalWrite(Reset, HIGH);
  delay(200);
  pinMode(Reset, OUTPUT);
  Serial.println("wait");
}

void loop()
{
  if (Serial.available() > 0)
  {
    Received = Serial.read();
  }
  // Notice that none of the action happens in loop() apart from reading millis()
  //   it just calls the functions that have the action code
  currentMillis = millis();   // capture the latest value of millis()
  //   this is equivalent to noting the time from a clock
  //   use the same time for all LED flashes to keep them synchronized
  // call the functions that do the work
  updateled1_State();
  updateled2_State();
  switchLeds();
}



//========
void updateled1_State()
{
  if (led1_State == LOW)
  {
    if (currentMillis - previousled1Millis >= blinkDuration)
    {
      led1_State = HIGH;
      previousled1Millis += blinkDuration;
    }
  }
  else
  {
    if (currentMillis - previousled3Millis >= led_Interval)
    {
      led1_State = LOW;
      previousled3Millis += led_Interval;
    }
  }
  if (Received == 'a' || Received == 'b')
  {
    led1_State = HIGH;
    led2_State = HIGH;
    led4_State = HIGH;
  }
}

//=========
void updateled2_State()
{
  if (led2_State == HIGH)
  {
    if (currentMillis - previousled3Millis >= led_Interval)
    {
      led2_State = LOW;
      previousled3Millis += led_Interval;
    }
  }
  else
  {
    if (currentMillis - previousled2Millis >= blinkDuration)
    {
      led2_State = HIGH;
      previousled2Millis += blinkDuration;
    }
  }
  if (Received == 'a' || Received == 'b')
  {
    led1_State = HIGH;
    led2_State = HIGH;
    led4_State = HIGH;
  }
}

//=======

void switchLeds()
{
  if (Received == '1' || Received == 'c')
  {
    // this is the code that actually switches the LEDs on and off
    digitalWrite(led1, led1_State);
    digitalWrite(led2, led2_State);
  }
  else
  {
    digitalWrite(led1, HIGH);
    digitalWrite(led2, HIGH);
    digitalWrite(led4, HIGH);
  }
  //-------- Program Reset both app and arduino program
  if (Received == '9')
  {
    Serial.println("wait");
    digitalWrite(Reset, LOW);
    digitalWrite(Reset, HIGH);
    delay(200);
  }
}
//-------- Normal Stop after preset time.
// if(Received == 'a'){

// digitalWrite(led1, led1_State);
// digitalWrite(led2, led2_State);

//------- Pause.
//if (Received == 'b')


// digitalWrite(led1, led1_State);
// digitalWrite(led2, led2_State);



//------ Play.
//if(Received == '1' && Received == 'c')


// digitalWrite(led1, led1_State);
// digitalWrite(led2, led2_State);

Please see I have uploaded a screenshot containing graph of waveforms of both LEDs .
The graph show how they should blink with Millis()
and than you for reply..
The graph will make it easy to catch the idea.

74younus:
OK I have an attachment please see it.
Please suggest some code.

Very easy. Start with the blink without delay example. Make it blink the led every 2 seconds.
Now, instead of alternating the led every two seconds, increment a counter variable: 0 => 1 => 2 => 3
When the counter reaches 4, reset back to 0.
When the counter is 3, turn LED1 ON, otherwise turn it OFF.
When the counter is 1, turn LED2 ON, otherwise turn it OFF.

Some code example !!

74younus:
Some code example !!

Take this in stages

Start with the blink without delay example. Make it blink the led every 2 seconds.

Post your code here when you have done that

74younus:
Some code example !!

It’s one variable assignment and 3 “if” statements. The steps are listed in post #12.
If you need an example for that, you need to go back and study the basics.

But as UKHeliBob says, post your best attempt and we will be happy to help. You will learn nothing if we just write the code for you.

74younus:
Some code example !!

I am very sure you mean it another way.
Three words and two attention-signs. This post has a high danger to be misunderstood as
"finish my project ! and hurry up!"
Again I'm very sure you mean it in a different way.
So to increase the willingness to help you a very good way would be to post your try how the code might look like and add a question related to your code.
If english is not your motherlanguage. Just type your post in your language into google translate. The grammar will not be fancy but this english will be understood. And more important: It show that you put some own effort into your learning.
So come on! Post a small piece of code what you think how this blinking might be working.

best regards Stefan

For your simplicity I posted only necessary working portion(loop section) of it . Do check if code or syntax is correct.

//increment a counter variable: 0 => 1 => 2 => 3 TICK
count++;

//When the counter reaches 4, reset back to 0. ????

//When the counter is 3, turn LED1 ON, otherwise turn it OFF. TICK - although missing a digitalWrite
if (count == 3){
  led1_State = LOW;
}

else {
  led1_State = HIGH;
}

//When the counter is 1, turn LED2 ON, otherwise turn it OFF. TICK - although missing a digitalWrite
if (count == 1){
  led2_State = LOW;
}

else {
  led2_State = HIGH;
  
}

//No idea where you got this from. Totally wrong.
count = 0;

I’ll give you 3/6 for your assignment. :wink:

This is a loop portion of my code That is why I want you suggest correct one.