sms based door lock

khizon18:
No. If you see my code in the loop I am not sending a message unless otherwise the attempt is equal to 3, I only reply to message when I received it. In the loop I only monitor incoming messages.. and I only monitor attempt then said messages and its part of the process to wait when sending messages.. However the problem is when I insert this code

 char pos =  sms.IsSMSPresent(SMS_UNREAD);

if (1==pos) {
  sms_detected();
}




If it is the problem what is the solution.. Should I use millis(); ?

sms.IsSMSPresent() is a function outside your code, in a library. I don't know what it does and if you want you can attach this library. I guess however that the function sends a command to the phone, something like AT+CGML="REC UNREAD", which lists the unread messages in the phone's memory. The problem is that it is blocking, it must wait for the modem response, and takes time even if there are no messages. You can measure the time it takes using millis(), this way:

loop() 
{
  unsigned long elapsed_millis;
  unsigned long start_millis = millis();

  char pos =  sms.IsSMSPresent(SMS_UNREAD);

  elapsed_millis = millis() - start_millis;
  Serial.print("millis spent in sms.IsSMSPresent: ");
  Serial.println(elapsed_millis);
  
...
}

And the problem is that IsSMSPresent is called on each loop(). It is more or less like adding a delay() of a couple of seconds (my guess), but you cannot replace it with some millis-based event because this is time actually spent communicating with the phone. There is no easy solution.

You have some large delay()s in your loop, and instead of doing nothing you could use this time to check for new messages. These delays however only happen when a door is locked or unlocked, so perhaps this is not a valid solution.

Another thing you can do is to perform the check at timed intervals. Suppose you can do with a check every 30 seconds. Then you create a variable which is reset when the check is executed, something like:

unsigned long last_check = millis();

loop()
{
  if (millis() - last_check > 30000)
  {
     // do the check
     last_check = millis();
  }
}

Obviously, every 30 seconds you'll have a significant change in performance.

The only alternative I see is changing the library code so that instead of a single blocking function you have different functions that are called during successive repetitions of loop().