Millis mayhem!!

int value = 49;
long previousMillis = 0;

long interval = 3000; //delay

void setup()
{
Serial.begin(9600);

}

void loop()
{

unsigned long currentMillis = millis();

if( currentMillis - previousMillis > interval)
{
Serial.write(val);
previousMillis = currentMillis + 2000; //2sec addition <<====
}

previousMillis = currentMillis;
}
}

can the line indicated by arrow( <<====) be used?? Does it work??
Please help! =(

That line can be used, it works, but...

  1. The variable named previousMillis now has a bad name, but even worse...

  2. That line is useless, considering that it is then followed by

previousMillis = currentMillis;

  1. It would help if you posted code using the code tags (the # button).
  2. It would help if you used the tools in the IDE to neaten your code.
  3. It would help if the brackets balanced.
  4. There is an assumption that previousMillis will start as zero. This may not be accurate, but I don't know your intentions.
     int value = 49;
     long previousMillis = 0;

     long interval = 3000; //delay

     void setup()
     {
     Serial.begin(9600);
     }

     void loop()
   {

       unsigned long currentMillis = millis();

       if( currentMillis - previousMillis > interval)
       {
         Serial.write(val);
         previousMillis = currentMillis + 2000; //2sec addition  <<====
        }

        previousMillis = currentMillis;
       }
   }

okay, here is the thing. I need two timings, one is the "interval" which i have already got, the other one which i intend to get is " interval + 2000ms " using the variables
previousMillis
currentMillis
each time the code transmits "val".

       if( currentMillis - previousMillis > interval)
       {
         Serial.write(val);
         previousMillis = currentMillis + 2000; //2sec addition  <<====
        }

        previousMillis = currentMillis; <========== this redefines the line above.. the 2sec is gone.
       }

Yes, I got to know. But can u write a code for my need, which satisfy the description i have mentioned in the comment above?

What are you trying to do? Your code is all wrong in so many ways.

bharath_r:

     int value = 49;

long previousMillis = 0;

long interval = 3000; //delay

void setup()
    {
    Serial.begin(9600);
    }

void loop()
  {

unsigned long currentMillis = millis();

if( currentMillis - previousMillis > interval)
      {
        Serial.write(val);
        previousMillis = currentMillis + 2000; //2sec addition  <<====
       }

previousMillis = currentMillis;
      }
  }



I need two timings, one is the "interval" which i have already got, the other one which i intend to get is " interval + 2000ms "

assuming the variable "interval" is a const long and not a variable long (as i don't see you writing to it anywhere in your code) are you saying you wish to obtain two values, one of which is the variable "interval" (which equals 3000) and the other "interval + 2000" (which equals 5000)?

Or were attempting to convey your meaning of the word "interval" differently within the same sentence?
Like where you say """ " interval + 2000ms " """ do you mean that this interval is not the same variable as the variable "interval"???

bharath_r:
using the variables
previousMillis
currentMillis
each time the code transmits "val".

Could you please elaborate a little on how this is connected with the previous statement?

Also i tried compiling you code, I got a compile time error:
'val' was not declared in this scope

Where does 'val' go? is val the other variable you are trying to calculate? where about does this get written to?

Even if one was to declare val and remove the extra brace it still won't work.

    int value = 49;
     long previousMillis = 0;

     long interval = 3000; //delay

     void setup()
     {
     Serial.begin(9600);
     }

     void loop()
   {

       unsigned long currentMillis = millis();

       if( currentMillis - previousMillis > interval)
       {
         Serial.write(val);
         previousMillis = currentMillis + 2000; //2sec addition  <<====
        }

        previousMillis = currentMillis;  // <<<----- This line needs to be in the if statement block.
       }
   }

Each time through loop() previousMillis is set to currentMillis so the interval can never be exceeded. val will never print. Even if it existed.

bharath_r:
Yes, I got to know. But can u write a code for my need, which satisfy the description i have mentioned in the comment above?

Try deleting it?

You are mixing long with unsigned long which you can get away with but may someday bite you.
Yes, the official example sketch Blink Without Delay mixes the types. It is a poor example for that.
All time variables should be unsigned and the same length, for beginners use unsigned long.

unsigned long interval = 3000UL; // the UL makes the constant 3000 be unsigned long. for long it is just L.

Arduino IDE in the Tools menu has Autoformat.
It not only keeps indents straight, it checks that they are balanced.
Use it OFTEN because when you do a lot and there is unbalanced {} or () then it will be harder to find.

     int value = 49;  // 49 is the same as '1' but less clear when reading code
     long previousMillis = 0;

     long interval = 3000; //delay

     void setup()
     {
     Serial.begin(9600);
     }

     void loop()
   {

       unsigned long currentMillis = millis();

       if( currentMillis - previousMillis > interval)
       {
         Serial.write(val);
         previousMillis = currentMillis + 2000; //2sec addition  <<====
        }

        previousMillis = currentMillis; <<<===== get rid of this line!
       }
   }

Have you seen this page? Your IDE has a copy of the sketch in the Examples section in the File menu.

it comes from here:

Some of us like to play with the examples a bit.
I also use BWD in sketches to make a running status light. If the blink is not right, the code is not right.

/* Blink without Delay -- with UL fixes and User Input
 
 Turns on and off a light emitting diode(LED) connected to a digital  
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.
 
 The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.
 
 
 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen
 modifed to add User-I/O as BWD2 1 Jan 2014 
 by GoForSmoke :-P
 
 This example code is in the public domain.
 
 
 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to 
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
unsigned long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
unsigned long tWait = 1000UL;           // interval at which to blink (milliseconds)
unsigned long userFactor = 100UL;

void usageMsg( void )
{
  Serial.println ( F ( __FILE__ ) );
  Serial.println( F("\nUSER CONTROL CHARS\n") );
  Serial.println( F("H for Help to print this message.") );
  Serial.println( F("F to blink faster, less factor") );
  Serial.println( F("S to blink slower, more factor") );
  Serial.println( F("digit x factor = blink\n") );
}

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

  Serial.begin( 57600 ); 
  Serial.println( F("\nBWD2 startup\n") );
  usageMsg(); 
}

void loop()
{
  // check to see if it's time to blink the LED; that is, if the 
  // difference between the current time and last time you blinked 
  // the LED is bigger than the interval at which you want to 
  // blink the LED.
  unsigned long currentMillis = millis();

  if ( currentMillis - previousMillis >= tWait ) 
  {
    // save the last time you blinked the LED 
    previousMillis = currentMillis;   

    // if the LED is off turn it on and vice-versa:
    ledState = !ledState; // ! is logical not, opposite

      // set the LED with the ledState of the variable:
    digitalWrite( ledPin, ledState );
  } // end of blink state change

    //    lowest priority is serial data because it is slow.
  if ( Serial.available() ) // this is the user input section -- it reads from serial monitor
  {
    char  serChar = Serial.read();

    if ( serChar >= '0' && serChar <= '9' ) // digits only
    {
      if ( serChar > '0' )
      {
        tWait = (long)( serChar - '0' ) * userFactor;
      }
      else
      {
        tWait = 10UL * userFactor;
      }
      Serial.print( F( "wait = " ));
      Serial.println( tWait );
    } 
    else if ((( serChar >= 'A' ) && ( serChar <= 'Z' )) || 
              (( serChar >= 'a' ) && ( serChar <= 'z' ))) // alphas only 
    {
      serChar &= 0xDF; // strips bit 5, makes lowercase alphas uppercase
      if ( serChar == 'F' ) // faster
      {
        if ( userFactor > 1UL )
        {
          userFactor /= 2UL; // increase the frequency
          tWait /= 2UL;
        }
        Serial.print( F("faster factor = ") );
        Serial.println( userFactor );
        Serial.print( F("wait = ") );
        Serial.println( tWait );
      }
      else if ( serChar == 'S' )  // slower
      {
        if ( userFactor < 1000UL )
        {
          userFactor *= 2UL;  // decrease the frequency
          tWait *= 2UL;
        }
        Serial.print( F("slower factor = ") );
        Serial.println( userFactor );
        Serial.print( F("wait = ") );
        Serial.println( tWait );
      }
      else if ( serChar == 'H' )  // help
      {
        usageMsg();
      }
    }
    // all other serial chars are ignored with no error messages
  } // end of serial available

  //    finished all tasks  
}

@bharath_r - you are not describing what you want clearly.

I reckon if you figure out how to describe your requirements clearly and in step-by-step detail then you will suddenly find that you can see how to write code to do it.

...R

There's one I missed. He defines value but serial writes val.