Go Down

Topic: Code modification (Read 628 times) previous topic - next topic

Alex1503

   I need LED to be on for 2sec and off for 5sec without using delay function.
How to modify the following code to do this?

const int ledPin1 =  13;          // pin number for relay 1

int ledState1 = LOW;             
long previousMillis1 = 0;       
long interval1 = 2000;          // interval at which to blink (milliseconds) for LED1
//long interval2 = 5000;     // interval at which LED1 is off (milliseconds)

void LED1()  //FUNCTION TO TURN ON AND OFF LED1.
{
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis1 > interval1)
  {
    previousMillis1 = currentMillis;   
    if (ledState1 == LOW)
      ledState1 = HIGH;
    else
      ledState1 = LOW;
    digitalWrite(ledPin1, ledState1);
  }
}

void setup()
{
  pinMode(ledPin1, OUTPUT);    // set the digital pin as output:
}

void loop()
{
  LED1();
}

tmd3

Think:  You're testing a variable, "interval1," to see if it's time to change the state of the LED.  You want the ontime and the offtime to be different.  You never change the value of "interval1."

What do you need to do?

johnwasser

Code: [Select]

 if(currentMillis - previousMillis1 > (ledState1 ? interval1 : interval2))


That's a shortcut version of:
Code: [Select]

 unsigned long interval;
 if (ledState1)
       interval = interval1;  //  LED stays ON for this time interval
 else
       interval = interval2;  //  LED stays OFF for this time interval
 if(currentMillis - previousMillis1 > interval)
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Alex1503

   Thank you!
   I am very new to coding.  So can you please show the whole code but not only idea.
In my code blinking is with equal interval, but I need LED to be off for longer time.
I am just learning.

johnwasser

Code: [Select]


const int ledPin1 =  13;          // pin number for relay 1

int ledState1 = LOW;             
unsigned long previousMillis1 = 0;       
const unsigned long interval1 = 2000;          // interval at which to blink (milliseconds) for LED1
const unsigned long interval2 = 5000;     // interval at which LED1 is off (milliseconds)

void LED1()  //FUNCTION TO TURN ON AND OFF LED1.
{
  unsigned long currentMillis = millis();

if(currentMillis - previousMillis1 > (ledState1 ? interval1 : interval2))
  {
    previousMillis1 = currentMillis;   
    ledState1 = !ledState1;
    digitalWrite(ledPin1, ledState1);
  }
}

void setup()
{
  pinMode(ledPin1, OUTPUT);    // set the digital pin as output:
}

void loop()
{
  LED1();
}
Send Bitcoin tips to: 1L3CTDoTgrXNA5WyF77uWqt4gUdye9mezN
Send Litecoin tips to : LVtpaq6JgJAZwvnVq3ftVeHafWkcpmuR1e

Nick Gammon

http://www.gammon.com.au/blink
http://www.gammon.com.au/electronics

Alex1503


Go Up