0

I'm executing this code to control a LED with GSM SIM900 message but there are two problems. First, it receives messages sometimes and some times doesn't. The second is that it doesn't execute the if conditions that are on the GSM message when received.

Is there a problem with my GSM module? Can any one help?

#include <SoftwareSerial.h>
SoftwareSerial gsm(9,10);
String msg;
const int LED = 13;

void setup() {
  gsm.begin(9600);
  Serial.begin(9600);
  Serial.println("PUMP CONTROL");
  Serial.println("t : to receive text");
  delay(1000);

  pinMode(LED, OUTPUT);
  digitalWrite(LED, LOW);
}

void loop() {
  if (Serial.available()>0)
  switch(Serial.read())
  {
    case 't':
    showSMS();
    break;
  }

  while(gsm.available() > 0)
  {
    Serial.write(gsm.read());
  }
  if ( msg == "ON")
  {
    Serial.println("ON");
    digitalWrite(LED, HIGH);
     Serial.println("ON1");
    delay(1000);
  } else if (msg == "OFF")
  {
    digitalWrite(LED, LOW);
    delay(1000);
  }
  if(msg != "") msg = "";
}

void showSMS()
{
 gsm.print("AT+CMGF=1\r");
 gsm.print("AT+CNMI=2,2,0,0,0\r");
 delay(1000);
 msg = "";
 while(gsm.available() > 0)
 {
  msg += gsm.read();
 }
 Serial.println(msg);
}
  • There are some basic commands that you should run before checking the messages. Like AT\r\n and check network status available or not and there are some more. – Vaibhav Apr 18 at 7:23
1

I’ve solved the condition problems by making the condition with the ASCII code of ON and OFF.

I replaced:

if ( msg == “ON”) 

with

if(msg.indexOf("ON")>=0) 

and replaced:

else if (msg == "OFF")

with

if(msg.indexOf("OFF")>=0) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.