Pir security system with remote on off using relay

This project i use ardunio nano
And I use relay module power on and off which goes to Pir sensors.

All the code and function work well until receive service sms or any kind of sms to sim 800L.

After relay on it detect motion because of pir sensor suddenly on that is normal . But after that function work well and detect motion .

If i send message not related to command and if it received any kind of sms service message it detect as motion detect and make call , THAT IS THE PROBLEM

What is the problem I cant understand :pleading_face::pleading_face:
Help me experts please......


#include <SoftwareSerial.h>

const String PHONE1 = "+94717897"; // Phone number 1
const String PHONE2 = "+94762";      // Phone number 2
const String PHONE3 = "+94781";      // Phone number 3

#define rxPin 6
#define txPin 7
#define buzzerPin 11 // Buzzer pin
#define RELAY_PIN 9  // Output for Relay Control

SoftwareSerial sim800(rxPin, txPin);

int pir_sensor1 = 2; // PIR sensor 1
int pir_sensor2 = 3; // PIR sensor 2

bool called = false; // To track if the call has been made

// Function to check the state of the relay (HIGH/ON or LOW/OFF)
bool relayStatus() {
  return digitalRead(RELAY_PIN) == HIGH;
}

void setup() {
  pinMode(pir_sensor1, INPUT);
  pinMode(pir_sensor2, INPUT);

  pinMode(buzzerPin, OUTPUT); // Set buzzer pin as OUTPUT
  pinMode(RELAY_PIN, OUTPUT); // Set the relay pin as OUTPUT
  digitalWrite(RELAY_PIN, LOW); // Initially turn off the relay (turn off PIR sensor)

  Serial.begin(9600);
  sim800.begin(9600);
  Serial.println("SIM800L software serial initialize");
  sim800.println("AT");
  delay(1000);

  while (!sim800.available()) {
    sim800.println("AT");
    delay(1000);
    Serial.println("Connecting...");
  }

  Serial.println("Connected!");
  sim800.println("AT+CMGF=1");  //Set SMS to Text Mode
  delay(1000);
  sim800.println("AT+CNMI=1,2,0,0,0");  //Procedure to handle newly arrived messages(command name in text: new message indications to TE)
  delay(1000);
  sim800.println("AT+CMGL=\"REC UNREAD\""); // Read Unread Messages
}

void loop() {
  while (sim800.available()) {
    String sms = sim800.readString();
    Serial.println("Received SMS: " + sms);

    // Ignore responses that match "Received SMS: AT+CMGDA=\"DEL ALL\" OK"
    if (sms.startsWith("Received SMS: ")) {
      continue;
    }

    // Check if the SMS contains a valid command
    if (sms.indexOf("ON1") != -1)
 {
      // Turn on the relay
      digitalWrite(RELAY_PIN, HIGH);
      sim800.println("Relay is ON"); // Send a response message
    } else if (sms.indexOf("OFF1") != -1) {
      // Turn off the relay
      digitalWrite(RELAY_PIN, LOW);
      sim800.println("Relay is OFF"); // Send a response message
    }

    // Delete Messages & Save Memory
  
  }

  // Check if any PIR sensor is HIGH, the relay is ON, and a call hasn't been made yet
  if (!called && relayStatus() && (digitalRead(pir_sensor1) == HIGH || digitalRead(pir_sensor2) == HIGH)) {
    Serial.println("Motion detected!");
    digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
    Serial.println("buzzer");
    delay(20000); // Buzzer stays on for 20 seconds
    digitalWrite(buzzerPin, LOW); // Turn off the buzzer

    Serial.println("calling....");
    delay(1000);
    sim800.println("ATD" + PHONE1 + ";"); // Call the 1st phone number
    called = true; // Set to true to avoid making more calls

    delay(25000); // Wait for 10 seconds (adjust as needed)
    sim800.println("ATH"); // Hang up the current call

    delay(5000); // Wait for 5 seconds before calling the next number
    sim800.println("ATD" + PHONE2 + ";"); // Call the 2nd phone number

    delay(25000); // Wait for 10 seconds (adjust as needed)
    sim800.println("ATH"); // Hang up the current call

    delay(5000); // Wait for 5 seconds before calling the last number
    sim800.println("ATD" + PHONE3 + ";"); // Call the 3rd phone number

    delay(25000); // Wait for 10 seconds (adjust as needed)
    sim800.println("ATH"); // Hang up the current call

    // Reset the 'called' variable to allow making calls again if motion is detected
    called = false;
    sim800.println("Searching");
  }
}

You have to apply message parsing. There are some examples in the internet. By using message parsing, you will be able to extract the content of the message. And you will need to write some condition in your code too. For example, if the message reads 'ON', the relay should be On.

1 Like

Does your sms really start with "Received SMS: " ? In the line before that you add that same text to the print statement.

Maybe it should be

if (sms.startsWith("AT+CMGDA=\"DEL ALL\" OK"))

or

if (sms.startsWith("AT+CMGDA=\"DEL ALL\""))

By the way, why did you try to place an image in the middle of the code :wink: ![IMG_3728|375x500](upload://6gByeNstbMfPOyvsbL0IfkMX6cR.jpeg)

1 Like

Image ? That was a mistake :nerd_face:,
Ok i ll try it but i cant understand can you explain deeply

You say those something interrupt with whe. sms receive

I tried servel code without using any mechanical thing to on and off the system by sending commnd . But it didnt work as I wish, so i add relay between pir power line now the relay on and off by sending command , when relay is off pir 5v supply not connect to it so the sensor are not work.

That is why i use relay to on off ,

Hi Haritha,

I think you are interested in finishing your project quick.
There is one very important thing to finish your project quick.
enough information that is easy to understand.

paragraph in Hindi

हाय हरिता,

मुझे लगता है कि आप अपना प्रोजेक्ट जल्दी पूरा करने में रुचि रखते हैं।
अपने प्रोजेक्ट को जल्दी पूरा करने के लिए एक बहुत महत्वपूर्ण बात है।
पर्याप्त जानकारी जिसे समझना आसान हो।
haay harita,

mujhe lagata hai ki aap apana projekt jaldee poora karane mein ruchi rakhate hain.
apane projekt ko jaldee poora karane ke lie ek bahut mahatvapoorn baat hai.
paryaapt jaanakaaree jise samajhana aasaan ho.

I am a somehow advanced hobby-programmer. So I have quite some experience with coding.

I have tried very hard to understand what you are describing. I do not understand what you want to say.

I assume the reason is that your english knowledge is limited. You should give yourself a gentle tap on your shoulder and finally use google-translate.

Write a very detailed description in your native language and then use google-translate for translating it to english.
This is the list of languages

Afrikaans	अफ्रीकी
Albanian	अल्बानियन
Amharic	अम्हारिक्
Arabic	अरबी
Armenian	अर्मेनियाई
Azerbaijani	आज़रबाइजानी
Assamese	असमिया
Aymara	आइमारा
Bambra	बम्बरा
Basque	बस्क
Belarussian	बेलारूसी
bengalisch	बंगाली
Bhojpuri	भोजपुरी
Birmanisch	बिरमनिश
Bosnian	बोस्नियाई
Bulgarian	बल्गेरियाई
cebuano	सिबुआनो
Chichewa	चिचेवा
Chinese (traditional)	चीनी पारंपरिक)
Chinese	चीनी
Danish	दानिश
history	इतिहास
German	जर्मन
Dhivehi	दिवेही
Dogri	डोगरी
history	इतिहास
Englisch	अंग्रेजी
Esperanto	एस्पेरांतो
Estnisch	एस्टनिश
ew	ईव
Filipino	filipino
Finnish	फिनिश
French	फ़्रेंच
Friesian	Friesian
Galician	गैलिशियन्
Georgian	जॉर्जीयन्
Greek	यूनानी
Guaraní	गुआरानी
Gujarati	गुजराती
Haitianish	हाईटियनिश
Hausa	होउसा
Hawaiian	हवाई
Hebrew	यहूदी
check	जाँच करना
Hindi	हिंदी
Hmong	हमोंग
Igbo	ईग्बो
Ilocano	इलोकानो
Indonesian	इन्डोनेशियाई
Irish	आयरिश
Icelandic	आइसलैंड का
Italian	इतालवी
Japanese	जापानी
Javanese	जावानीस
Yiddish	यहूदी
Kannada	कन्नडा
Kasachich	कसाचिच
Catalan	कातालान
Khmer	खमेर
Kinyarwanda	किन्यारवाण्डा
Kyrgyz	किरगिज़
Konkani	कोंकणी
Korean	कोरियाई
Corsican	कॉर्सिकन
Krio	क्रियो
Croatian	क्रोएशियाई
Kurdish (Kurmandschi)	कुर्दिश (कुर्मंदस्ची)
Kurdish (Sorani)	कुर्दिश (सोरानी)
Lao	लाओ
Latein	देर में
lettuce	सलाद पत्ता
Lingala	लिंगाला
Lithuanian	लिथुआनियाई
Uganda	युगांडा
Luxembourgish	लक्जमबर्गिश
Maithili	मैथिली
Malagasy	मालागासी
malayalam	मलयालम
Malaysian	मलेशियाई
history	इतिहास
Maltese	मोलतिज़
Māori	माओरी
Marathi	मराठी
Macedonian	मेसीडोनियन
Meitei (Manipuri)	मैतेई (मणिपुरी)
Mizo	मिज़ो
Mongolian	मंगोलियन
Nepalese	नेपाली
Dutch	डच
Norwegian	नार्वेजियन
Odia (Oriya)	उड़िया (उड़िया)
Oromo	ओरोमो
Pashtu	पश्तू
Persian	फ़ारसी
Polish	पोलिश
Portuguese	पुर्तगाली
Punjabi	पंजाबी
Quechua	केचुआ
Romanian	रोमानियाई
Russian	रूसी
Samoan	सामोन
Sanskrit	संस्कृत
Schottisch-Gälisch	शोटिश-गैलिश
Swedish	स्वीडिश
Sepedi	सेपेडी
Serbian	सर्बियाई
Sesotho	सेसोथो
Shona	सोणा
Sindhi	सिंधी
Sinhalese	लंका का
Slovak	स्लोवाक
Slowenisch	स्लोवेनिश
Somali	सोमाली
Spanish	स्पैनिश
Sundanese	सुंडानी
Swahili	swahili
Tadschikisch	Tadschikisch
Tamil	तामिल
Tatarish	तातारिश
telugu	तेलुगु
Thai	थाई
Tigrinya	तिग्रिन्या
Czech	चेक
Tsonga	त्सोंगा
turkish	तुर्की
Turkmenisch	तुर्कमेनिश
twi	ट्वी
Uigurish	उइगुरिश
Ukrainian	यूक्रेनी
Hungarian	हंगेरी
Urdu	उर्दू
history	इतिहास
Usbekisch	Usbekisch
Vietnamese	वियतनामी
Welsh	वेल्श
Xhosa	षोसा
Yoruba	योरूबा
Zulu	ज़ुलु

If I paste your username "Haritha Ranathunga" into google-translate google says
recognised language Hindi

Not sure if this is correct. Anyway you yourself know exactly what your native language your motherlanguage is.

Even in case that google translate uses some weird words. The bigger number of words of a translation will make it better understandable than three or four poor worded english sentences.

So please please please - at least - give google-translate a try.

Google-සිංහල ඉංග්‍රීසි පරිවර්තනය කරන්න

I dont know hindi language im from srilanka and my language is sinhala , thank you ill try.

This is my project friend

I use ardunio nano
Sim 800L
2 pir sensors
And realy

Diagram is correct there is no issue with the circuit ,

Relay is connect between power source and pir sensors . Relay can switch power which goes to pir sensors.
Ok

Relay on off by sending sms command.

Relay is off position
Now i send sms not the command it dosent do anything elas of false trigger as motion detect.

Then i send command to relay ON
Now
Relay is on position

Now is the problem happen.
When sim received any call or sms from carrier service like service sms, credit balance sms

First it detect as motion then make buzzer high and make call and after that it show the sms is received in serial monitor .

It again happen when i send OFF command and it make call end of the all function it show command message and then switch off relay.

I connect DMM to PIR sensor if any error happen with them but they are not triggered. If unwanted sms received to sim 800L it start to show as motion detect on serial monitor and make call.

That is the problem i faced can you understand it

This happens after turning on the relay, when the sim receives a service message or something else, it says motion detect, then the call function is turned on, but then the message is displayed. I want to stop this from happening. All other functions in the code work fine
Then, when I sent the command to turn off the relay, the motion was detected again and when the call function was finished, the relay was turned off after reading the message it received.

:smiling_face_with_tear:Wrote it with google translator​:relieved:

OK now that you have written that your native language is sinhala you can use google-translate.

I will do a demonstration how good this works by writing

  1. in german
  2. google-translate to japanese
  3. google-translate japanese to english
  4. google-translate english to sinhala

So here is the final result german--->----japanese---->------english----->-----sinhala

ක්‍රමලේඛන දෝෂ සෙවීමට ඇති හොඳම ක්‍රමය වන්නේ ඔබේ වැඩසටහනේ බොහෝ ස්ථානවල අනුක්‍රමික ප්‍රතිදානය එක් කිරීමයි.

මෙම අනුක්‍රමික මුද්‍රණය අනුක්‍රමික මොනිටරයට පහත දේ ලියයි:
- කොන්දේසිය සත්‍ය හෝ අසත්‍ය නම්
- විචල්‍යයේ නියම අන්තර්ගතය

මෙමගින් ඔබගේ කේතයේ සිදුවන්නේ කුමක්ද යන්න පිළිබඳව සවිස්තරාත්මක අවබෝධයක් ලබා දෙනු ඇත.
ඔබට අවශ්‍ය දේ කිරීමට ඔබේ වැඩසටහන ලියන ආකාරය ද එය ඔබට කියයි.

kramalēkhana dōṣa sevīmaṭa æti hon̆dama kramaya vannē obē væḍasaṭahanē bohō sthānavala anukramika pratidānaya ek kirīmayi.

mema anukramika mudraṇaya anukramika moniṭarayaṭa pahata dē liyayi:
- kondēsiya satya hō asatya nam
- vicalyayē niyama antargataya

memagin obagē kētayē siduvannē kumakda yanna piḷiban̆dava savistarātmaka avabōdhayak labā denu æta.
obaṭa avaśya dē kirīmaṭa obē væḍasaṭahana liyana ākāraya da eya obaṭa kiyayi.

additionally I made these translations:
german--->-----sinhala---japanese-----german
too see how much the translation will deviate from the original text.
It does deviate but the main thing is still easy to understand and this is what counts!

Your last post is still difficult to understand. I understand some parts but not everything.
So please please please give google-translate a try

as an exception the paragraph above google-translated to sinhala

ඊට අමතරව මම මෙම පරිවර්තන සිදු කළෙමි:
ජර්මන්--->-----සිංහල---ජපන්-----ජර්මන්
පරිවර්තනය මුල් පිටපතෙන් කොපමණ වෙනස් වේද යන්න ද බලන්න.
එය අපගමනය වන නමුත් ප්රධාන දෙය ** තවමත් තේරුම් ගැනීමට පහසු වන අතර මෙය වැදගත් වේ**!

ඔබගේ අවසන් සටහන තවමත් තේරුම් ගැනීමට අපහසුය. මට සමහර කොටස් තේරෙනවා නමුත් හැම දෙයක්ම නැහැ.
එබැවින් කරුණාකර ගූගල් පරිවර්තනය උත්සාහ කර බලන්න
īṭa amatarava mama mema parivartana sidu kaḷemi:
jarman--->-----siṁhala---japan-----jarman
parivartanaya mul piṭapaten kopamaṇa venas vēda yanna da balanna.
eya apagamanaya vana namut pradhāna deya ** tavamat tērum gænīmaṭa pahasu vana atara meya vædagat vē**!

obagē avasan saṭahana tavamat tērum gænīmaṭa apahasuya. maṭa samahara koṭas tērenavā namut hæma deyakma næhæ.
ebævin karuṇākara gūgal parivartanaya utsāha kara balanna

google-translate sinhala to english Google-සිංහල ඉංග්‍රීසි පරිවර්තනය කරන්න

Many English words are used for some of the Sinhala words and that is why they were not translated from Sinhala.

මේ කෝඩ් එක අප්ලෝඩ් කරාට පසුව එය හොදින් වැඩ කරන්වා. එහි අන්තර්ගත රිලේ ඔන් සහ ඕෆ් විදාන , මෝශන් එකක් ඩිටෙක්ට් වුනාම කෝල් ෆන්ක්ශන් එක හරියට වැඩ කරන්වා.

නමුත් වෙනත් ආකාරයක එස්එම්එස් එකක් හෝ කෝල් එකක් සිම් 800 මොඩියුලයට ලැබුන විට එය මෝශන් එකක් ඩිටෙක්ට් වුනා සේ සලකා කෝල් ෆන්ක්ශන් එක ක්‍රියාත්මක වීම සිදුවෙනවා.

තවද රිලේ මොඩියුලය ඕෆ් කරන්න කමාන්ඩ් මැසේජ් එක යැවීම සිදුකල පසු එය මුලින්ම මෝශන් එකක් ඩිටෙක්ට් වුනා සේ ස්ලකා කෝල් සහ බසර් ෆන්ක්ශන් එක ඔන් වෙනවා ඉන් පසු තමා ලැබුන කම්න්ඩ් එක එක්සිකියුට් කරන්නෙ.

නමුත් මම බලාපොරොත්තු වෙන්නෙ මට අවශ වෙලාවට සිස්ටම් එක ඔන් කිරීම සහ මෝශන් එකක් ඩිටෙක්ට් වුනොත් කෝල් ෆන්ක්ශන් එක ඔන් වෙලා ක්‍රියාත්මක වීම.

නමුත් සිදුවන්නේ මෝශන් එකකින් තොරව ලැබෙන මැසේජ් මෝශන් එකක් ලෙස සලකා ක්‍රියාත්මක වීම.

After uploading this code it works fine. It contains relay on and off sensors, when a motion is detected, the call function works properly.

But when the SIM 800 module receives a different type of SMS or a call, the call function is activated considering that it has detected a motion.

And after sending the command message to turn off the relay module, it first detects a motion, the Slaka call and buzzer function is turned on, after that it executes the received command.

But I want the system to turn on when I need it and if a motion is detected the call function will turn on and run.

But what happens is that the message received without a motion is treated as a motion

You are talking about a "call-function".
Please use the name that is used inside your code if you are writing about this function.

If you want to proceed quick it is always a good investion to take additional 10 minutes to go through your text a second and a thrid time to check
have a named everything explicitly ?
And then to re-write the text to always use the exact names for everything.

This will save you 20 minutes up to hours of waiting for the real answer.
If you use generalised words like "it" "the code" "that" all that happends is waiting until somebody reads and then asks back "what do you mean exactly???"
and then you will have to write the exact description anyway.

Writing down the exact description in sinhala will make it easy for you to write it.
Then let do google-translate the translation.
best regards Stefan

ප්‍රශ්නය තමා

කමාන්ඩ් මැසේජ් එකක් යවලා රිලේ එක ඔන් වුනාට පස්සේ සිම් එකට වෙන මොකක් හරි මැසේජ් එකක් ආවම මෝශන් ඩිටෙක්ට් කියලා සීරියල් මොනිටර් එකේ ප්‍රින්ට් වෙලා කොල් ගන්නවා නම්බර්ස් වලට ,

@Haritha1995

you should really take the effort of

translating to english!

This is the english speaking / writing forum.

As an exception and for the convenience of all english users your text google-translated

best regards Stefan

here is your code with the exact same functionality as your original code but with the following modifications:

  • it uses SafeStrings instead of String to avoid memory-corruption
  • I inserted a function printToSim800_AND_serial that prints everything that is sended to your Sim800-modul to the serial monitor exactly 1 on 1 the same characters.
  • at the top if the code there are debugging macros. You can ignore them at the moment. These macros are for future use for further debugging developping your code

To make it compile you have to install the SafeString-library

It does compile but I don't have your hardware so you will have to test it
and then post the serial output not as a picture but as code-section.

// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298

#define dbg(myFixedText, variableName) \
  Serial.print( F(#myFixedText " "  #variableName"=") ); \
  Serial.println(variableName);

#define dbgi(myFixedText, variableName,timeInterval) \
  { \
    static unsigned long intervalStartTime; \
    if ( millis() - intervalStartTime >= timeInterval ){ \
      intervalStartTime = millis(); \
      Serial.print( F(#myFixedText " "  #variableName"=") ); \
      Serial.println(variableName); \
    } \
  }

#define dbgc(myFixedText, variableName) \
  { \
    static long lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }

#define dbgcf(myFixedText, variableName) \
  { \
    static float lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *

#include <SoftwareSerial.h>
#include <SafeString.h>

cSF(myMessage_SS, 64);
cSF(sms_SS, 128);

cSF(PHONE1, 16, "+94717897");
cSF(PHONE2, 16, "+94762");
cSF(PHONE3, 16, "+94781");

cSF(ATD, 4, "ATD");
cSF(ATH, 4, "ATH");

unsigned long MyTestTimer = 0;                   // Timer-variables MUST be of type unsigned long
const byte    OnBoard_LED = 13;

//String sms;

/*
  const String PHONE1 = "+94717897"; // Phone number 1
  const String PHONE2 = "+94762";    // Phone number 2
  const String PHONE3 = "+94781";    // Phone number 3
*/

#define rxPin 6
#define txPin 7
#define buzzerPin 11 // Buzzer pin
#define RELAY_PIN 9  // Output for Relay Control

SoftwareSerial sim800(rxPin, txPin);

int pir_sensor1 = 2; // PIR sensor 1
int pir_sensor2 = 3; // PIR sensor 2

bool called = false; // To track if the call has been made

// Function to check the state of the relay (HIGH/ON or LOW/OFF)
bool relayStatus() {
  return digitalRead(RELAY_PIN) == HIGH;
}

void setup() {
  Serial.begin(9600);
  Serial.println("Setup-Start");
  PrintFileNameDateTime();

  pinMode(pir_sensor1, INPUT);
  pinMode(pir_sensor2, INPUT);

  pinMode(buzzerPin, OUTPUT); // Set buzzer pin as OUTPUT
  pinMode(RELAY_PIN, OUTPUT); // Set the relay pin as OUTPUT
  digitalWrite(RELAY_PIN, LOW); // Initially turn off the relay (turn off PIR sensor)

  sim800.begin(9600);
  Serial.println("SIM800L software serial initialized");
  myMessage_SS = "AT";
  //sim800.println("AT");
  printToSim800_AND_serial(myMessage_SS);
  delay(1000);

  Serial.println("trying to connect to Sim800...");
  while (!sim800.available()) {
    //sim800.println("AT");
    myMessage_SS = "AT";
    printToSim800_AND_serial(myMessage_SS);
    delay(1000);
  }

  Serial.println("Connected to Sim800!");
  //sim800.println("AT+CMGF=1");  //Set SMS to Text Mode
  myMessage_SS = "AT+CMGF=1";
  printToSim800_AND_serial(myMessage_SS);
  delay(1000);
  //sim800.println("AT+CNMI=1,2,0,0,0");  //Procedure to handle newly arrived messages(command name in text: new message indications to TE)
  myMessage_SS = "AT+CNMI=1,2,0,0,0";
  printToSim800_AND_serial(myMessage_SS);

  delay(1000);
  //sim800.println("AT+CMGL=\"REC UNREAD\""); // Read Unread Messages
  myMessage_SS = "AT+CMGL=\"REC UNREAD\"";
  printToSim800_AND_serial(myMessage_SS);
}

void loop() {
  while (sim800.available()) {
    //String sms = sim800.readString();
    sms_SS = sim800.readString().c_str();
    Serial.print("Received SMS: #");
    Serial.print(sms_SS);
    Serial.println("#");

    // Ignore responses that match "Received SMS: AT+CMGDA=\"DEL ALL\" OK"
    //if (sms.startsWith("Received SMS: ")) {
    if (sms_SS.startsWith("Received SMS: ")) {
      continue;
    }

    // Check if the SMS contains a valid command
    //if (sms.indexOf("ON1") != -1)
    if (sms_SS.indexOf("ON1") != -1)
    {
      // Turn on the relay
      digitalWrite(RELAY_PIN, HIGH);
      //sim800.println("Relay is ON"); // Send a response message
      myMessage_SS = "Relay is ON";
      printToSim800_AND_serial(myMessage_SS);

    } 
    //else if (sms.indexOf("OFF1") != -1) {
    else if (sms_SS.indexOf("OFF1") != -1) {
      // Turn off the relay
      digitalWrite(RELAY_PIN, LOW);
      //sim800.println("Relay is OFF"); // Send a response message
      myMessage_SS = "Relay is OFF";
      printToSim800_AND_serial(myMessage_SS);
    }
    // Delete Messages & Save Memory
  }

  // Check if any PIR sensor is HIGH, the relay is ON, and a call hasn't been made yet
  if (!called && relayStatus() && (digitalRead(pir_sensor1) == HIGH || digitalRead(pir_sensor2) == HIGH)) {
    Serial.println("Motion detected!");
    digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
    Serial.println("buzzer");
    delay(20000); // Buzzer stays on for 20 seconds
    digitalWrite(buzzerPin, LOW); // Turn off the buzzer

    Serial.println("calling....");
    delay(1000);
    //sim800.println("ATD" + PHONE1 + ";"); // Call the 1st phone number
    myMessage_SS  = ATD;
    myMessage_SS += PHONE1;
    myMessage_SS += ";";
    called = true; // Set to true to avoid making more calls
    printToSim800_AND_serial(myMessage_SS);

    delay(25000); // Wait for 10 seconds (adjust as needed)
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    delay(5000); // Wait for 5 seconds before calling the next number
    //sim800.println("ATD" + PHONE2 + ";"); // Call the 2nd phone number
    myMessage_SS  = ATD;
    myMessage_SS += PHONE2;
    myMessage_SS += ";";
    printToSim800_AND_serial(myMessage_SS);

    delay(25000); // Wait for 10 seconds (adjust as needed)
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    delay(5000); // Wait for 5 seconds before calling the last number
    //sim800.println("ATD" + PHONE3 + ";"); // Call the 3rd phone number
    myMessage_SS  = ATD;
    myMessage_SS += PHONE3;
    myMessage_SS += ";";
    printToSim800_AND_serial(myMessage_SS);

    delay(25000); // Wait for 10 seconds (adjust as needed)
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    // Reset the 'called' variable to allow making calls again if motion is detected
    called = false;
    sim800.println("Searching");
  }
}


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("  compiled ") );
  Serial.print( F(__DATE__) );
  Serial.print( F(" ") );
  Serial.println( F(__TIME__) );
}


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);

  if ( TimePeriodIsOver(MyBlinkTimer, BlinkPeriod) ) {
    digitalWrite(IO_Pin, !digitalRead(IO_Pin) );
  }
}


void printToSim800_AND_serial(SafeString& pointerTo_SS) {
  sim800.println(pointerTo_SS.c_str() );
  Serial.print("send to sim800 #");
  Serial.print(pointerTo_SS);
  Serial.println("#");
}
1 Like

Thank you very much i ll check it :handshake::smiling_face_with_three_hearts:


Setup-Start
Code running comes from file 
C:\Users\Haritha Ranathunga\Desktop\aluth_code_eka_august_7_haduwe\aluth_code_eka_august_7_haduwe.ino
  compiled Aug  7 2023 19:09:41
SIM800L software serial initialized
send to sim800 #AT#
trying to connect to Sim800...
Connected to Sim800!
send to sim800 #AT+CMGF=1#
send to sim800 #AT+CNMI=1,2,0,0,0#
send to sim800 #AT+CMGL="REC UNREAD"#
Received SMS: #AT

OK
AT+CMGF=1

OK
AT+CNMI=1,2,0,0,0

OK
AT+CMGL="REC UNREAD"

OK
#
Received SMS: #
+CMT: "+94717897246","","23/08/07,19:10:21+22"
ON12
#
send to sim800 #Relay is ON#
Received SMS: #Relay is ON
#
Motion detected!
buzzer
calling....
send to sim800 #ATD+94717897246;#
send to sim800 #ATH#
send to sim800 #ATD+94762;#
send to sim800 #ATH#
send to sim800 #ATD+94781;#
send to sim800 #ATH#
Received SMS: #ATD+94717897246;

OK
ATH

OK
ATD+94762;

OK

NO CARRIER
ATH
Searching

OK
#
Motion detected!
buzzer
calling....
send to sim800 #ATD+94717897246;#
send to sim800 #ATH#
send to sim800 #ATD+94762;#
send to sim800 #ATH#
send to sim800 #ATD+94781;#
send to sim800 #ATH#
Received SMS: #
+CMT: "+94717897246","","23/08/07,19:12:36+22"
**Test sms after relay on**
AATH
Searching

OK
#
19:16:16.695 -> Motion detected!
19:16:16.695 -> buzzer
19:16:36.689 -> calling....
19:16:37.735 -> send to sim800 #ATD+94717897246;#

You see when i send sms it trigger as motion detect

That is the problem ifaced with code.

Very good that this code-version is working.
In the meantime I have added more serial printing for analysing test this code-version and post the serial output as a code-section

// MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START * MACRO-START *
// a detailed explanation how these macros work is given in this tutorial
// https://forum.arduino.cc/t/comfortable-serial-debug-output-short-to-write-fixed-text-name-and-content-of-any-variable-code-example/888298

#define dbg(myFixedText, variableName) \
  Serial.print( F(#myFixedText " "  #variableName"=") ); \
  Serial.println(variableName);

#define dbgi(myFixedText, variableName,timeInterval) \
  { \
    static unsigned long intervalStartTime; \
    if ( millis() - intervalStartTime >= timeInterval ){ \
      intervalStartTime = millis(); \
      Serial.print( F(#myFixedText " "  #variableName"=") ); \
      Serial.println(variableName); \
    } \
  }

#define dbgc(myFixedText, variableName) \
  { \
    static long lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }

#define dbgcf(myFixedText, variableName) \
  { \
    static float lastState; \
    if ( lastState != variableName ){ \
      Serial.print( F(#myFixedText " "  #variableName" changed from ") ); \
      Serial.print(lastState); \
      Serial.print( F(" to ") ); \
      Serial.println(variableName); \
      lastState = variableName; \
    } \
  }
// MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END * MACRO-END *

#include <SoftwareSerial.h>
#include <SafeString.h>

cSF(myMessage_SS, 64);
cSF(sms_SS, 128);

cSF(PHONE1, 16, "+94717897");
cSF(PHONE2, 16, "+94762");
cSF(PHONE3, 16, "+94781");

cSF(ATD, 4, "ATD");
cSF(ATH, 4, "ATH");

unsigned long MyTestTimer = 0;                   // Timer-variables MUST be of type unsigned long
const byte    OnBoard_LED = 13;

//String sms;

/*
  const String PHONE1 = "+94717897"; // Phone number 1
  const String PHONE2 = "+94762";    // Phone number 2
  const String PHONE3 = "+94781";    // Phone number 3
*/

#define rxPin 6
#define txPin 7
#define buzzerPin 11 // Buzzer pin
#define RELAY_PIN 9  // Output for Relay Control

SoftwareSerial sim800(rxPin, txPin);

int pir_sensor1 = 2; // PIR sensor 1
int pir_sensor2 = 3; // PIR sensor 2

bool called = false; // To track if the call has been made

// Function to check the state of the relay (HIGH/ON or LOW/OFF)
bool relayStatus() {
  return digitalRead(RELAY_PIN) == HIGH;
}

void setup() {
  Serial.begin(9600);
  Serial.println("Setup-Start");
  PrintFileNameDateTime();

  pinMode(pir_sensor1, INPUT);
  pinMode(pir_sensor2, INPUT);

  pinMode(buzzerPin, OUTPUT); // Set buzzer pin as OUTPUT
  pinMode(RELAY_PIN, OUTPUT); // Set the relay pin as OUTPUT
  digitalWrite(RELAY_PIN, LOW); // Initially turn off the relay (turn off PIR sensor)

  sim800.begin(9600);
  Serial.println("SIM800L software serial initialized");
  myMessage_SS = "AT";
  //sim800.println("AT");
  printToSim800_AND_serial(myMessage_SS);
  delay(1000);

  Serial.println("trying to connect to Sim800...");
  while (!sim800.available()) {
    //sim800.println("AT");
    myMessage_SS = "AT";
    printToSim800_AND_serial(myMessage_SS);
    delay(1000);
  }

  Serial.println("Connected to Sim800!");
  //sim800.println("AT+CMGF=1");  //Set SMS to Text Mode
  myMessage_SS = "AT+CMGF=1";
  printToSim800_AND_serial(myMessage_SS);
  delay(1000);
  //sim800.println("AT+CNMI=1,2,0,0,0");  //Procedure to handle newly arrived messages(command name in text: new message indications to TE)
  myMessage_SS = "AT+CNMI=1,2,0,0,0";
  printToSim800_AND_serial(myMessage_SS);

  delay(1000);
  //sim800.println("AT+CMGL=\"REC UNREAD\""); // Read Unread Messages
  myMessage_SS = "AT+CMGL=\"REC UNREAD\"";
  printToSim800_AND_serial(myMessage_SS);
}

void loop() {
  
  dbgc("Top of loop",called);// whenever variable with name "called" changes its value print the change to serial monitor
  dbgc("Top of loop",relayStatus() ); // whenever the function relayStatus() results in a changed value print the change to serial monitor
  dbgc("Top of loop",digitalRead(pir_sensor1) );
  dbgc("Top of loop",digitalRead(pir_sensor2) );

  while (sim800.available()) {
    //String sms = sim800.readString();
    sms_SS = sim800.readString().c_str();
    Serial.print("Received SMS: #");
    Serial.print(sms_SS);
    Serial.println("#");

    // Ignore responses that match "Received SMS: AT+CMGDA=\"DEL ALL\" OK"
    //if (sms.startsWith("Received SMS: ")) {
    if (sms_SS.startsWith("Received SMS: ")) {
      dbg("sms_SS.startsWith('Received SMS: ')",sms_SS.startsWith("Received SMS: "));
      continue;
    }

    // Check if the SMS contains a valid command
    //if (sms.indexOf("ON1") != -1)
    if (sms_SS.indexOf("ON1") != -1)
    {
      dbg("if (sms_SS.indexOf('ON1') != -1)",sms_SS.indexOf("ON1") );
      // Turn on the relay
      digitalWrite(RELAY_PIN, HIGH);
      //sim800.println("Relay is ON"); // Send a response message
      myMessage_SS = "Relay is ON";
      printToSim800_AND_serial(myMessage_SS);

    } 
    //else if (sms.indexOf("OFF1") != -1) {
    else if (sms_SS.indexOf("OFF1") != -1) {
      dbg("else if sms_SS.indexOf('OFF1') != -1",sms_SS.indexOf("OFF1") );
      // Turn off the relay
      digitalWrite(RELAY_PIN, LOW);
      //sim800.println("Relay is OFF"); // Send a response message
      myMessage_SS = "Relay is OFF";
      printToSim800_AND_serial(myMessage_SS);
    }
    // Delete Messages & Save Memory
  }

  dbgc("before motion detect",called);// whenever variable with name "called" changes its value print the change to serial monitor
  dbgc("before motion detect",relayStatus() ); // whenever the function relayStatus() results in a changed value print the change to serial monitor
  dbgc("before motion detect",digitalRead(pir_sensor1) );
  dbgc("before motion detect",digitalRead(pir_sensor2) );
  // Check if any PIR sensor is HIGH, the relay is ON, and a call hasn't been made yet
  if (!called && relayStatus() && (digitalRead(pir_sensor1) == HIGH || digitalRead(pir_sensor2) == HIGH) ) {
    Serial.println("Motion detected!");
    digitalWrite(buzzerPin, HIGH); // Turn on the buzzer
    Serial.println("buzzer");
    Serial.println("delay(20000)");
    delay(20000); // Buzzer stays on for 20 seconds
    digitalWrite(buzzerPin, LOW); // Turn off the buzzer
    Serial.println("delay(20000) done");

    Serial.println("calling....");
    Serial.println("delay(1000)");
    delay(1000);
    //sim800.println("ATD" + PHONE1 + ";"); // Call the 1st phone number
    myMessage_SS  = ATD;
    myMessage_SS += PHONE1;
    myMessage_SS += ";";
    called = true; // Set to true to avoid making more calls
    printToSim800_AND_serial(myMessage_SS);

    Serial.println("delay(25000)");
    delay(25000); // Wait for 10 seconds (adjust as needed)
    Serial.println("delay(25000) done");
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    Serial.println("delay(5000)");
    delay(5000); // Wait for 5 seconds before calling the next number
    Serial.println("delay(5000) done");
    //sim800.println("ATD" + PHONE2 + ";"); // Call the 2nd phone number
    myMessage_SS  = ATD;
    myMessage_SS += PHONE2;
    myMessage_SS += ";";
    printToSim800_AND_serial(myMessage_SS);

    Serial.println("delay(26000)");
    delay(26000); // Wait for 10 seconds (adjust as needed)
    Serial.println("delay(26000) done");
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    Serial.println("delay(6000)");
    delay(6000); // Wait for 5 seconds before calling the last number
    //sim800.println("ATD" + PHONE3 + ";"); // Call the 3rd phone number
    Serial.println("delay(6000) done");
    myMessage_SS  = ATD;
    myMessage_SS += PHONE3;
    myMessage_SS += ";";
    printToSim800_AND_serial(myMessage_SS);

    Serial.println("delay(27000)");
    delay(27000); // Wait for 10 seconds (adjust as needed)
    Serial.println("delay(27000) done");
    //sim800.println("ATH"); // Hang up the current call
    myMessage_SS  = ATH;
    printToSim800_AND_serial(myMessage_SS);

    // Reset the 'called' variable to allow making calls again if motion is detected
    called = false;
    sim800.println("Searching");
  }
}


void PrintFileNameDateTime() {
  Serial.println( F("Code running comes from file ") );
  Serial.println( F(__FILE__) );
  Serial.print( F("  compiled ") );
  Serial.print( F(__DATE__) );
  Serial.print( F(" ") );
  Serial.println( F(__TIME__) );
}


// easy to use helper-function for non-blocking timing
boolean TimePeriodIsOver (unsigned long &startOfPeriod, unsigned long TimePeriod) {
  unsigned long currentMillis  = millis();
  if ( currentMillis - startOfPeriod >= TimePeriod ) {
    // more time than TimePeriod has elapsed since last time if-condition was true
    startOfPeriod = currentMillis; // a new period starts right here so set new starttime
    return true;
  }
  else return false;            // actual TimePeriod is NOT yet over
}


void BlinkHeartBeatLED(int IO_Pin, int BlinkPeriod) {
  static unsigned long MyBlinkTimer;
  pinMode(IO_Pin, OUTPUT);

  if ( TimePeriodIsOver(MyBlinkTimer, BlinkPeriod) ) {
    digitalWrite(IO_Pin, !digitalRead(IO_Pin) );
  }
}


void printToSim800_AND_serial(SafeString& pointerTo_SS) {
  sim800.println(pointerTo_SS.c_str() );
  Serial.print("send to sim800 #");
  Serial.print(pointerTo_SS);
  Serial.println("#");
}

best regards Stefan

First motion detect normally happen because power on relay and current pass to pir sensors.

And 2 motion detect because I send sms to test

3rd one i move infront of pir sensor


19:43:25.186 -> Setup-Start
19:43:25.186 -> Code running comes from file 
19:43:25.186 -> C:\Users\Haritha Ranathunga\Desktop\aluth_code_eka_august_7_haduwe\aluth_code_eka_august_7_haduwe.ino
19:43:25.285 ->   compiled Aug  7 2023 19:37:25
19:43:25.336 -> SIM800L software serial initialized
19:43:25.385 -> send to sim800 #AT#
19:43:26.352 -> trying to connect to Sim800...
19:43:26.402 -> Connected to Sim800!
19:43:26.402 -> send to sim800 #AT+CMGF=1#
19:43:27.384 -> send to sim800 #AT+CNMI=1,2,0,0,0#
19:43:28.401 -> send to sim800 #AT+CMGL="REC UNREAD"#
19:43:29.435 -> Received SMS: #AT

19:43:29.435 -> OK
19:43:29.435 -> AT+CMGF=1

19:43:29.468 -> OK
19:43:29.468 -> AT+CNMI=1,2,0,0,0

19:43:29.468 -> OK
19:43:29.518 -> AT+CMGL="REC UNREAD"

19:43:29.518 -> OK
19:43:29.518 -> #
19:44:27.052 -> Received SMS: #
19:44:27.052 -> +CMT: "+94717897246","","23/08/07,19:44:35+22"
19:44:27.148 -> ON12
19:44:27.148 -> #
19:44:27.148 -> "if (sms_SS.indexOf('ON1') != -1)" sms_SS.indexOf("ON1")=50
19:44:27.182 -> send to sim800 #Relay is ON#
19:44:28.190 -> Received SMS: #Relay is ON
#
19:44:28.190 -> "before motion detect" relayStatus() changed from 0 to 1
19:44:28.232 -> "before motion detect" digitalRead(pir_sensor1) changed from 0 to 1
19:44:28.315 -> "before motion detect" digitalRead(pir_sensor2) changed from 0 to 0
19:44:28.398 -> "Top of loop" relayStatus() changed from 0 to 1
19:44:28.432 -> "before motion detect" digitalRead(pir_sensor1) changed from 1 to 0
19:44:41.393 -> Motion detected!
19:44:41.393 -> buzzer
19:44:41.393 -> delay(20000)
19:45:01.376 -> delay(20000) done
19:45:01.376 -> calling....
19:45:01.411 -> delay(1000)
19:45:02.379 -> send to sim800 #ATD+94717897246;#
19:45:02.429 -> delay(25000)
19:45:27.380 -> delay(25000) done
19:45:27.380 -> send to sim800 #ATH#
19:45:27.429 -> delay(5000)
19:45:32.429 -> delay(5000) done
19:45:32.429 -> send to sim800 #ATD+94762;#
19:45:32.480 -> delay(26000)
19:45:58.426 -> delay(26000) done
19:45:58.426 -> send to sim800 #ATH#
19:45:58.460 -> delay(6000)
19:46:04.426 -> delay(6000) done
19:46:04.426 -> send to sim800 #ATD+94781;#
19:46:04.496 -> delay(27000)
19:46:31.464 -> delay(27000) done
19:46:31.464 -> send to sim800 #ATH#
19:46:32.478 -> Received SMS: #ATD+94717897246;

19:46:32.526 -> OK
19:46:32.526 -> ATH

19:46:32.526 -> OK
19:46:32.526 -> ATD+94762;

19:46:32.526 -> OK
19:46:32.559 -> 
19:46:32.559 -> NO CARRIER
ATH
Searching

19:46:32.559 -> OK
19:46:32.592 -> #
19:47:07.155 -> "before motion detect" digitalRead(pir_sensor2) changed from 0 to 1
19:47:07.191 -> Motion detected!
19:47:07.191 -> buzzer
19:47:07.191 -> delay(20000)
19:47:27.182 -> delay(20000) done
19:47:27.182 -> calling....
19:47:27.223 -> delay(1000)
19:47:28.181 -> send to sim800 #ATD+94717897246;#
19:47:28.222 -> delay(25000)
19:47:53.209 -> delay(25000) done
19:47:53.209 -> send to sim800 #ATH#
19:47:53.256 -> delay(5000)
19:47:58.238 -> delay(5000) done
19:47:58.238 -> send to sim800 #ATD+94762;#
19:47:58.271 -> delay(26000)
19:48:24.238 -> delay(26000) done
19:48:24.238 -> send to sim800 #ATH#
19:48:24.287 -> delay(6000)
19:48:30.241 -> delay(6000) done
19:48:30.241 -> send to sim800 #ATD+94781;#
19:48:30.287 -> delay(27000)
19:48:57.233 -> delay(27000) done
19:48:57.233 -> send to sim800 #ATH#
19:48:58.302 -> Received SMS: #
19:48:58.302 -> +CMT: "+94717897246","","23/08/07,19:47:15+22"
19:48:58.369 -> test messge aATH
Searching

19:48:58.369 -> OK
19:48:58.403 -> #
19:48:58.403 -> "before motion detect" digitalRead(pir_sensor2) changed from 1 to 0
19:49:51.249 -> Motion detected!
19:49:51.249 -> buzzer
19:49:51.249 -> delay(20000)
19:50:11.237 -> delay(20000) done
19:50:11.237 -> calling....
19:50:11.273 -> delay(1000)
19:50:12.263 -> send to sim800 #ATD+94717897246;#
19:50:12.298 -> delay(25000)
19:50:37.257 -> delay(25000) done
19:50:37.257 -> send to sim800 #ATH#
19:50:37.333 -> delay(5000)
19:50:42.279 -> delay(5000) done
19:50:42.279 -> send to sim800 #ATD+94762;#
19:50:42.331 -> delay(26000)
19:51:08.302 -> delay(26000) done
19:51:08.302 -> send to sim800 #ATH#
19:51:08.346 -> delay(6000)
19:51:14.293 -> delay(6000) done
19:51:14.293 -> send to sim800 #ATD+94781;#
19:51:14.364 -> delay(27000)
19:51:41.312 -> delay(27000) done
19:51:41.312 -> send to sim800 #ATH#
19:51:42.393 -> Received SMS: #ATD+94717897246;

19:51:42.393 -> OK
19:51:42.393 -> 
19:51:42.393 -> BUSY
19:51:42.393 -> ATH

19:51:42.393 -> OK
19:51:42.393 -> ATD+94762;

19:51:42.428 -> OK
19:51:42.428 -> 
19:51:42.428 -> NO ATH
Searching

19:51:42.428 -> OK
19:51:42.462 -> #