millis - need help

hello everyone. i`m strugling with Millis 8( Task is to use Serial.println("alarm") if a condition is true for at least 5 seconds. Else - do nothing and reset previosly started timer if it has been started.

Here is my solution:

#include<Wire.h>
/*some code*/
unsigned long alerttime;
 
void setup(){

 /*some code*/
 
  
}
void loop(){
  

  /*some code*/
  if ((x<=100 || x>=230) && (y>=180 || y<20))
     {
        alerttime = millis();
     }
  if 
     if(millis() - alerttime > 5000) {
     Serial.println("iunocare alert : critical baby position ");
     }
   else
     {
        Serial.println(" ");
     } 

delay(100);
}

but somehow i have an opposite result ))) i have an alert message when i should have none and dont see an alarm message when it should be.

Thanks!

Partial code sucks, what is the variable "alert" and where is it set?

rev_never:
if a condition is true for at least 5 seconds. Else - do nothing

The way to deal with that is to think about it backwards (or upside down).

Reset the timer every time the condition fails and then if the timer gets as far as 5 seconds you know it is safe to do stuff. Something like this

if (condition == false) {
  startMillis = millis();
}
if (millis() - startMillis >= 5000) {
  // condition has been true for 5 secs
}

...R

PS.. don't mix delay() and millis() in the same program because you will probably miss some of the millis() tests.

Thanks a lot now with == false everything works! Have a nice day)

Danois90:
Partial code sucks, what is the variable "alert" and where is it set?

Sorry the ALERT part was from another version of my tries. I`ve delited it from the code already ) Have a nice day

First, anytime you're working with non-int data types, it's a good idea to let the compiler and reader know that, so this expression:

  • if(millis() - alerttime > 5000) {*

is better documented if you write it as:

  • if(millis() - alerttime > 5000UL) { // Note the UL type qualifier*

Also, before you post your code, place the cursor in the Source Code window of the IDE and press Ctrl-T to reformat your code to a common C style.

econjack , thanks for the tip, man!