How to fix millis

I'm trying to use millis to be a non blocking delay.

When serial receives a 1 led should blink till it receives a 0.

This just turns the led on and off.

I can't find the error of my way here Thanks for the help.

#define LED 3
unsigned long interval = 1000; // the time we need to wait
unsigned long previousMillis = 0; // millis() returns an unsigned long.

bool ledState = false; // state variable for the LED

void setup() {
  pinMode(LED, OUTPUT);
  digitalWrite(LED, ledState);
  Serial.begin(9600);
  Serial.println("LED on Serial " + String(LED));
}

void loop() {
  
  if (Serial.available()) {
    char s = Serial.read();
    if (s == '1') {
      unsigned long currentMillis = millis(); // grab current time
      // check if "interval" time has passed (1000 milliseconds)
      if ((unsigned long)(currentMillis - previousMillis) >= interval) {

        ledState = !ledState; // "toggles" the state
        digitalWrite(LED, ledState); // sets the LED based on ledState
        // save the "current" time
        previousMillis = millis();
      }

      Serial.println("on");
    }
    if (s == '0') {
      digitalWrite(LED, LOW);
      Serial.println("off");
    }
  }
}

I tried this too don't seem to work still just can turn led on and off no toggle

#define LED 3
unsigned long interval = 1000; // the time we need to wait
unsigned long previousMillis = 0; // millis() returns an unsigned long.

bool ledState = false; // state variable for the LED

void setup() {
  pinMode(LED, OUTPUT);
  digitalWrite(LED, ledState);
  Serial.begin(9600);
  Serial.println("LED on Serial " + String(LED));
}

void loop() {
  
  if (Serial.available()) {
    char s = Serial.read();
    if (s == '1') {
      unsigned long currentMillis = millis(); // grab current time
      // check if "interval" time has passed (1000 milliseconds)
      if ((unsigned long)(currentMillis - previousMillis) >= interval) {

        ledState = !ledState; // "toggles" the state
        digitalWrite(LED, ledState); // sets the LED based on ledState
        // save the "current" time
        previousMillis = millis();
      }

      Serial.println("on");
    }
    else if (s == '0') {
      digitalWrite(LED, LOW);
      Serial.println("off");
    }
  }
}

Have a look at my reply #9 here, where I gave a solution to the exact same question for a different member.

I used a second bool state called blinkMode, as well as the ledState that you used.

edit, btw, I don't think millis() is actually broken :wink:

When you receive a 1, make an enableFlag = 1.

When you receive a 0, make the enableFlag = 0.

When the enableFlag = 1, flash the LED.

larryd:
When you receive a 1, make an enableFlag = 1.

When you receive a 0, make the enableFlag = 0.

When the enableFlag = 1, flash the LED.

Yeah that’s pretty much what my code does, with a couple of extras for debugging to show it’s entering or exiting blinkMode.

Looks good kind of what thought but I'm not that good at C

be80be:
Looks good

Does that mean my code does what you want?

wilfredmedlin:
Does that mean my code does what you want?

Yes your code worked going to fix what I wrote. Good job

I guess it's a coincidence that you and Lemon Foam asked the same question-maybe a problem from a book or something.

Anyway,glad it helped.

Hell I don't no I just read about millis for about 4 hours. i wrote some code that turned a led on on the esp when you send a 1 0r a 0 to it. I figured I give a blink ago at it LOL.

Well as you no a delay hold up the code till it's done.

So I used millis but it never runs the delay I'm not a programmer I'm a hardware guy I fix the broken junk that people break.

These forums are nice but not everyone knows what to look for I've read 100 post on millis and then posted this one.

But thank you both for posting.

wilfredmedlin I have to say tho I’ve read your code like 4 times and see something about "if then "
statement I have not seen before.

C is not top down like basic is

Sorry, I don't understand the question about if...then. There is no "if then" in C, just "if" with the "then" implied.

Here is a more advanced way of doing the same thing.
I show to you only to wet your appetite.

//                          m a k e T i m e r
//**********************************************************************
struct makeTimer
{
  public:
    unsigned long StartTime;   //the time this Timer was (re)started
    unsigned long Interval;    //interval time we are looking for
    bool          Restart;     //do we restart Timer timing automatically. true = restart
    bool          EnableFlag;  //is "this Timer" enabled/allowed to be accessed, true = enabled

}; //END of structure       m a k e T i m e r


//**********************************************************************
//Okay, let's create and define our Timer objects.
//**********************************************************************
//We will make our Timers

//***************************
makeTimer FlashTimer =            //"FlashTimer" is the name we are giving this Timer
{
  0, 250UL, true, false           //StartTime, Interval, Restart, EnableFlag
};                                //Toggle LED every 1/4 second
//***************************
//makeTimer whatEver =            //"whatEver" is the name we are giving this Timer
//{
//  0, 5000UL, true, true         //StartTime, Interval, Restart, EnableFlag
//};                              //Toggle LED every 5 seconds
//***************************

//More timers can go here  <----<<<<


const byte LED  = 3;

//                             s e t u p ( )
//======================================================================
void setup()
{
  Serial.begin(9600);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);  //LOW = LED OFF

} //END of:                    s e t u p ( )


//                              l o o p ( )
//======================================================================
void loop()
{
  //*********************************************
  if (Serial.available())
  {
    char s = Serial.read();
    
    //****************
    if (s == '1')
    {
      FlashTimer.EnableFlag = true;
    }

    //****************
    else if (s == '0')
    {
      FlashTimer.EnableFlag = false;
      digitalWrite(LED, LOW);  //LOW = LED OFF
    }
  }

  //*********************************************
  if (CheckTimer(FlashTimer))
  {
    //Toggle LED
    digitalWrite(LED, !digitalRead(LED));
  }


} //END of:                     l o o p ( )


//======================================================================
//                           F U N C T I O N S
//======================================================================


//                         C h e c k T i m e r ( )
//======================================================================
// Used when actions are needed 'after' a period of time.
boolean CheckTimer(makeTimer &TimerX)
{
  //StartTime  = the time TimerX was (re)started
  //Interval   = interval/delay we are looking for
  //Restart    = do we restart TimerX automatically
  //EnableFlag = is TimerX enabled/allowed to be accessed

  //Is TimerX enabled and has TimerX expired?
  if (TimerX.EnableFlag == true && millis() - TimerX.StartTime >= TimerX.Interval)
  {
    //Should we restart TimerX automatically?
    if (TimerX.Restart == true)
    {
      TimerX.StartTime = millis();           //get ready for the next iteration
      //or use
      //TimerX.StartTime += TimerX.Interval;
    }

    //This Timer did expired
    return true;
  }

  //This timer did not expire or it is disabled
  return false;

} //END of:                 C h e c k T i m e r ( )



//======================================================================
//                             END OF CODE
//======================================================================

See this link if you are interested in seeing more.

Like this

If { // This is basically the same as basic 

}

In basic there are no {} you use " if xxx==x do stuff here then "

In C It's if xxxx==x {do sfuff here }

I get lost with the {} and the () and ; LOL but I learning a lot wish I would of started with C LOL

larryd I'm looking at your code too I really want get the hang of C or C++ arduino ide can use both from what i see.

Thanks larryd

Here's the syntax of an if. You always need this part, with the condition in ( ):

if (x>5)

After that you can do this:

if (x>5) y= 10;

But that way is limited to only having one thing to do after the condition. So if there's more than one, you put those things inside { }:

if (x>5)
{
y= 10;
z=20;
}

If you don't use the { }, only the first thing will be controlled by the if, the other/s will always happen.

Many folk, including me, always use the { } even when there is only one thing to do:

if (x>5)
{
y= 10;
}

NEVER put a ; right after the ( ) like below, becasue then NOTHING will be controlled by the if, and everything in the { } will always happen:

if (x>5);
{
y= 10;
z=20;
}

And you can do what you like as far as typing, so this:

if (x>5)
{
y= 10;
z=20;
}

.... is the same as this:

if (x>5){
y= 10;
z=20;}

.... and the same as this:

if (x>5){y= 10;z=20;}

An "else" follows on thus:

if (x>5)
{
y= 10;
z=20;
}
else
{
y=50;
}

Some people type it like this }else{, which I think looks bloody stupid:

if (x>5)
{
y= 10;
z=20;
}else{
y=50;
}

There's a big advantage to having every { and every } on their own lines: when you do a control-T in the IDE it makes everything very tidy and easy to read.

cool