Facing problem with LED sequence code

Hi,

I have build a LED sequencer. The 6 LED’s are attached to pin number 3,5,6,9,10,11. The reason I have picked only the PWM pins are that I want to give fading effect later.

I also have included a variable ‘duration’ to note the time in milliseconds for determining how long each LED should remain on.

The problem I am having is very strange to me. The code works absolutely fine with ‘duration’ values like 20/40/60/80/100/120 but it stops working after 2 sequences with values like 10/30/50/70/90/110/130.

I would appreciate some help here. I have pasted the code for your understanding.

It may seem to you that I have prepared a very complicated code for a simple job, I am trying to learn it through hard way.

int pins[]={3,5,6,9,10,11};
unsigned long duration=60;
char dir='l';
unsigned long last_time=millis();
int i=0;
void setup(){
  for(int x=0;x<6;x++){
    pinMode(pins[x],OUTPUT);
  }
}
void loop(){
  if((millis()-last_time)==duration){
    last_time=millis();
    if(dir=='l')
    {
      if(i!=-1){
        digitalWrite(pins[i], HIGH);
        if(i!=0){
          int low = i-1;
          digitalWrite(pins[low], LOW);
        }
      }
      if(i<6){
        i=i+1;
      }
      if(i>5){
        dir='r';
      }
    }
    if(dir=='r')
    {
      if(i!=6){
        digitalWrite(pins[i], LOW);
        if(i!=0){
          int high=i-1;
          digitalWrite(pins[high], HIGH);
        }
      }
      if(i>-1){
        i=i-1;
      }
      if(i<0){
        dir='l';
      }
    }
  }
}

Try changing

if((millis()-last_time)==duration)

to

if((millis()-last_time)>=duration)

It may seem to you that I have prepared a very complicated code for a simple job

You have certainly done that.

I am trying to learn it through hard way.

Don't, make your code as readable and simple as possible. Once you got a working code, re-factor it.

I'll check your code and update.

The suggestion from UKHeliBob has worked, thanks. I have changed :

if((millis()-last_time)==duration)

to:

if((millis()-last_time)>=duration)

That was a good learning for me. And I am working on simplification of the code.

The suggestion from UKHeliBob has worked, thanks.

Glad to have been of service. Do you understand why it worked ?

UKHeliBob:

Do you understand why it worked ?

This is what I have figured out. The program itself is taking time to complete the loop which is hampering exact matching with the duration length. When >= compactor is used, it is also accepting slightly higher than duration.

Is my understanding okay?

Either that or millis() does not always increment by 1. Either way an exact comparison will sometimes fail.