ArduinoArduino UnoExact chip

SMS switch (SIM800L)

Text "LED ON" or "LED OFF" to the SIM800L and pin 13 follows; the board texts back what it did.

SMS switch (SIM800L) in Argynix Lab

The code

sketch.inoC++
// An LED switched by SMS: a SIM800L on SoftwareSerial (pins 7 and 8). Send it "LED ON"
// or "LED OFF" from the modem's settings in the inspector; the board answers by SMS.
#include <SoftwareSerial.h>

SoftwareSerial gsm(7, 8); // RX (from the module's TXD), TX (to its RXD)
const char *OWNER = "+919876543210";

String readLine(uint32_t ms) {
  String s;
  uint32_t t = millis();
  while (millis() - t < ms) {
    while (gsm.available()) {
      char c = gsm.read();
      if (c == '\n') return s;
      if (c != '\r') s += c;
    }
  }
  return s;
}

void command(const char *at, uint32_t wait = 500) {
  gsm.println(at);
  uint32_t t = millis();
  while (millis() - t < wait) while (gsm.available()) Serial.write(gsm.read());
}

void sms(const char *to, const char *text) {
  gsm.print("AT+CMGS=\"");
  gsm.print(to);
  gsm.println("\"");
  delay(300);
  gsm.print(text);
  gsm.write(26); // Ctrl-Z sends it
  delay(1500);
  while (gsm.available()) Serial.write(gsm.read());
}

void setup() {
  pinMode(13, OUTPUT);
  Serial.begin(9600);
  gsm.begin(9600);
  delay(3000);
  for (int i = 0; i < 3; i++) command("AT", 300); // it learns 9600 baud from "AT"
  command("ATE0");
  command("AT+CMGF=1");          // text mode
  command("AT+CNMI=2,1,0,0,0");  // tell us when an SMS arrives
  Serial.println("Ready: send it LED ON or LED OFF");
}

void loop() {
  String line = readLine(100);
  if (!line.startsWith("+CMTI:")) return;
  int index = line.substring(line.indexOf(',') + 1).toInt();
  gsm.print("AT+CMGR=");
  gsm.println(index);
  // The answer: a blank line, +CMGR: "REC UNREAD","+91…", then the text.
  String head;
  uint32_t t = millis();
  while (!head.startsWith("+CMGR:") && millis() - t < 2000) head = readLine(500);
  String text = readLine(500);
  Serial.print("SMS: ");
  Serial.println(text);
  if (text.indexOf("ON") >= 0) {
    digitalWrite(13, HIGH);
    sms(OWNER, "LED is ON");
  } else if (text.indexOf("OFF") >= 0) {
    digitalWrite(13, LOW);
    sms(OWNER, "LED is OFF");
  }
  command("AT+CMGD=1,4");        // clear the inbox
}