Request Sensor Data via SMS using Arduino and SIM900 GSM Shield

In this project we’re going to show you how to request sensor data via SMS with the Arduino. As an example we’re going to request the temperature and humidity from a DHT11 sensor. To send and receive SMS with the Arduino we’re going to use the SIM900 GSM shield.

When you send an SMS to the Arduino with the message “STATE”, it replies with the latest temperature and humidity readings.

Before proceeding with this tutorial we recommend the following resources:

First, watch the video demonstration

SIM900 GSM Shield

There are several modules you can use to send and receive SMS with the Arduino. We did this project using the SIM900 GSM shield and that’s the shield we recommend you to get.

The SIM900 GSM shield is shown in figure below:

For an introduction to the GSM shield, and how to set it up, read the Guide to SIM900 GSM GPRS Shield with Arduino.

Parts Required

Here’s a list of all the components needed for this project:

You can use the preceding links or go directly to MakerAdvisor.com/tools to find all the parts for your projects at the best price!

Preliminary steps

Before getting started with your SIM900 GSM module, you need to consider some aspects about the SIM card and the shield power supply.

Prepaid SIM card

We recommend that you use a prepaid plan or a plan with unlimited SMS for testing purposes. Otherwise, if something goes wrong, you may need to pay a huge bill for hundreds of SMS text messages sent by mistake. In this tutorial we’re using a prepaid plan with unlimited SMS.

The shield uses the original SIM card size, not micro or nano. If you have micro or nano you may consider getting a SIM card size adapter.

Turn off the PIN lock

To use the SIM card with the shield, you need to turn off the pin lock. The easiest way to do this, is to insert the SIM card in your smartphone and turn off the pin lock in the phone security settings.

In my case, I need to go through: Settings > Advanced Settings > Security > SIM lock and turn off the lock sim card with pin.

Getting the right power supply

The shield has a DC jack for power as shown in figure below.

Next to the power jack there is a toggle switch to select the power source. Next to the toggle switch on the board, there is an arrow indicating the toggle position to use an external power supply – move the toggle switch to use the external power supply as shown above.

To power up the shield, it is advisable to use a 5V power supply that can provide 2A as the one shown below.

You can find the right power adapter for this shield here. Make sure you select the model with 5V and 2A.

Setting up the SIM900 GSM Shield

The following steps show you how to set up the SIM900 GSM shield.

1) Insert the SIM card into the SIM card holder. You need a SIM card with the standard size. The shield is not compatible with micro or nano SIM cards. If you need, you may get a sim card size adapter. Also, it is advisable to use a SIM card with a prepaid plan or unlimited SMS.

2) Confirm the antenna is well connected.

3) On the serial port select, make sure the jumper cap is connected as shown in figure below to use software serial.

 

4) Power the shield using an external 5V power supply. Double-check that you have the external power source selected as we’ve mentioned earlier.

5) To power up/down the shield press the power key for about 2 seconds.

6) Then, the Status LED will light up and the NetLight LED will blink every 800 ms until it finds the network. When it finds the network the NetLight LED will start blinking every three seconds.

7) You can test if the shield is working properly by sending AT commands from the Arduino IDE using an FTDI programmer – as we’ll show below.

Testing the Shield with FTDI programmer

You don’t need to do this step to get the shield working properly. This is an extra step to ensure that you can communicate with your GSM shield and send AT commands from the Arduino IDE serial monitor. For that, you need an FTDI programmer as the one shown in figure below.

1) Connect the FTDI programmer to the GSM shield as shown in figure below.

2) Open the Arduino IDE and select the right COM port.

3) Open the Serial monitor.

4) Select 19200 baud rate – the shield default setting is 19200 – and Carriage return. Write AT at the box highlighted in red and then press enter. See figure below.

5) The shield will respond with OK, if everything is working properly.

Now that you know the shield is working properly, you are ready to start building the project.

Schematics

The figure below shows the circuit schematics for this project.

You have to connect the SIM900 GSM shield and the DHT11 temperature and humidity sensor to the Arduino as shown in the figure below.

Installing the DHT library

To read from the DHT sensor, you must have the DHT library installed. If you don’t have the DHT library installed, follow the instructions below:

  1. Click here to download the DHT-sensor-library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get DHT-sensor-library-master folder
  3. Rename your folder from DHT-sensor-library-master to DHT
  4. Move the DHT folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Installing the Adafruit_Sensor library

To use the DHT temperature and humidity sensor, you also need to install the Adafruit_Sensor library. Follow the next steps to install the library in your Arduino IDE:

  1. Click here to download the Adafruit_Sensor library. You should have a .zip folder in your Downloads folder
  2. Unzip the .zip folder and you should get Adafruit_Sensor-master folder
  3. Rename your folder from Adafruit_Sensor-master to Adafruit_Sensor
  4. Move the Adafruit_Sensor folder to your Arduino IDE installation libraries folder
  5. Finally, re-open your Arduino IDE

Code

The following code reads the temperature and humidity from the DHT sensor and sends them via SMS when you send an SMS to the Arduino with the message “STATE”.

You need to modify the code provided with the phone number your Arduino should reply the readings to. The code is well commented for you to understand the purpose of each line of code. Don’t upload the code now. Scroll down and read the explanation below the code.

/*
 * Rui Santos 
 * Complete Project Details https://randomnerdtutorials.com
 */


// Include DHT library and Adafruit Sensor Library
#include "DHT.h"
#include <Adafruit_Sensor.h>
//Include Software Serial library to communicate with GSM
#include <SoftwareSerial.h>

// Pin DHT is connected to
#define DHTPIN 2
  
// Uncomment whatever type of sensor you're using
#define DHTTYPE DHT11   // DHT 11 
//#define DHTTYPE DHT22   // DHT 22  (AM2302)
//#define DHTTYPE DHT21   // DHT 21 (AM2301)

// Initialize DHT sensor for normal 16mhz Arduino
DHT dht(DHTPIN, DHTTYPE);

// Create global varibales to store temperature and humidity
float t; // temperature in celcius
float f; // temperature in fahrenheit
float h; // humidity

// Configure software serial port
SoftwareSerial SIM900(7, 8);

// Create variable to store incoming SMS characters
char incomingChar;

void setup() {
  dht.begin();
  
  Serial.begin(19200); 
  SIM900.begin(19200);

  // Give time to your GSM shield log on to network
  delay(20000);
  Serial.print("SIM900 ready...");

  // AT command to set SIM900 to SMS mode
  SIM900.print("AT+CMGF=1\r"); 
  delay(100);
  // Set module to send SMS data to serial out upon receipt 
  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
}

void loop(){
  if (SMSRequest()){
    if(readData()){
      delay(10);
      // REPLACE THE X's WITH THE RECIPIENT'S MOBILE NUMBER
      // USE INTERNATIONAL FORMAT CODE FOR MOBILE NUMBERS
      SIM900.println("AT + CMGS = \"+XXXXXXXXXX\"");
      delay(100);
      // REPLACE WITH YOUR OWN SMS MESSAGE CONTENT
      String dataMessage = ("Temperature: " + String(t) + "*C " + " Humidity: " + String(h) + "%");
      // Uncomment to change message with farenheit temperature
      // String dataMessage = ("Temperature: " + String(f) + "*F " + " Humidity: " + String(h) + "%");      
      
      // Send the SMS text message
      SIM900.print(dataMessage);
      delay(100);
      // End AT command with a ^Z, ASCII code 26
      SIM900.println((char)26); 
      delay(100);
      SIM900.println();
      // Give module time to send SMS
      delay(5000);  
    }
  }
  delay(10); 
}

boolean readData() {
  //Read humidity
  h = dht.readHumidity();
  // Read temperature as Celsius
  t = dht.readTemperature();
  // Read temperature as Fahrenheit
  f = dht.readTemperature(true);

  // Compute temperature values in Celcius
  t = dht.computeHeatIndex(t,h,false);

  // Uncomment to compute temperature values in Fahrenheit
  //f = dht.computeHeatIndex(f,h,false);
  
  // Check if any reads failed and exit early (to try again).
  if (isnan(h) || isnan(t) || isnan(f)) {
    Serial.println("Failed to read from DHT sensor!");
    return false;
  }
  Serial.print("Humidity: "); 
  Serial.print(h);
  Serial.print(" %\t");
  Serial.print("Temperature: "); 
  Serial.print(t);
  Serial.print(" *C ");
  //Uncomment to print temperature in Farenheit
  //Serial.print(f);
  //Serial.print(" *F\t");
  return true;
}

boolean SMSRequest() {
  if(SIM900.available() >0) {
    incomingChar=SIM900.read();
    if(incomingChar=='S') {
      delay(10);
      Serial.print(incomingChar);
      incomingChar=SIM900.read();
      if(incomingChar =='T') {
        delay(10);
        Serial.print(incomingChar);
        incomingChar=SIM900.read();
        if(incomingChar=='A') {
          delay(10);
          Serial.print(incomingChar);
          incomingChar=SIM900.read();
          if(incomingChar=='T') {
            delay(10);
            Serial.print(incomingChar);
            incomingChar=SIM900.read();
            if(incomingChar=='E') {
              delay(10);
              Serial.print(incomingChar);
              Serial.print("...Request Received \n");
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}

View raw code

Importing libraries

First, you include the libraries needed for this project: the DHT libary to read from the DHT sensor and the SoftwareSerial library to communicate with the SIM900 GSM module.

#include "DHT.h"
#include <Adafruit_Sensor.h>
#include <SoftwareSerial.h>

DHT sensor

Then, you tell the Arduino that the DHT data pin is connected to pin 2, select the DHT sensor type and create a dht instance. The code is compatible with other DHT sensors as long as you define the one you’re using in the code.

#define DHTPIN 2
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);

You also create float variables to store the temperature and humidity values.

float t; // temperature in celcius
float f; // temperature in fahrenheit
float h; // humidity

GSM shield

The following line configures the software serial on pins 7 and 8. Pin 7 is being configure as RX and pin 8 as TX.

SoftwareSerial SIM900(7, 8);

You also create a char variable to store the incoming SMS characters.

char incomingChar;

setup()

In the setup(), you begin the DHT and the SIM900 shield. The SIM900 shield is set to text mode and you also set the module to send the SMS data to the serial monitor when it receives it. This is done with the following two lines, respectively:

SIM900.print("AT+CMGF=1\r"); 
SIM900.print("AT+CNMI=2,2,0,0,0\r");

Functions

We create a function to read the temperature and humidity called readData(). This function stores the values on the t and h variables. The code uses temperature in Celsius, but it is prepared if you want Fahrenheit instead – the code is commented on where you should make the changes.

We also create a function that checks if the incoming message is equal to STATE – the SMSRequest() function. This functions returns true if the Arduino receives a message with the text STATE and false if not.  You read the SMS incoming characters using:

incomingChar = SIM900.read();

loop()

In the loop(), you check if there was an SMS request with the SMSRequest() function – you check if the Arduino received a STATE message. If true, it will read the temperature and humidity and send it via SMS to you.

The number the Arduino answers to is set at the following line:

SIM900.println("AT + CMGS = \"XXXXXXXXXXXX\"");

Replace the XXXXXXXXXXXX with the recipient’s phone number.

Note: you must add the number according to the international phone number format. For example, in Portugal the number is preceded by +351XXXXXXXXX.

Then, you store the message you want to send in the dataMessage variable. Finally you send the SMS text message using:

SIM900.print(dataMessage);

Demonstration

When you send the STATE message to the Arduino, it replies with the sensor data.

Watch the video at the beginning of the post for a more in depth project demo.

Wrapping Up

This is a great project to get you started with the SIM900 GSM shield. You’ve learned how to read and send SMS text messages with the Arduino.

You can apply the concepts learned in pretty much any project. Here’s some ideas of projects:

  • Surveillance system that sends an SMS when it detects movement
  • Control a relay via SMS
  • Request specific sensor data from a collection of sensors by adding more conditions to the code

If you like Arduino, you’ll certainly like these 25 Arduino Step-by-step Projects.



Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »
Learn how to build a home automation system and we’ll cover the following main subjects: Node-RED, Node-RED Dashboard, Raspberry Pi, ESP32, ESP8266, MQTT, and InfluxDB database DOWNLOAD »

Enjoyed this project? Stay updated by subscribing our newsletter!

65 thoughts on “Request Sensor Data via SMS using Arduino and SIM900 GSM Shield”

  1. Hi all,
    the SIM900 GSM is still a 2G interface … and most providers will soon get up the 2G standard to move at least o 4G standard … as announced for the end of 2018

    Reply
    • Here in Australia the 2G networks have been shut down. Most carriers now use 4G as a minimum. The SIM900 is a very old device. There are 3G and 4G modules out there but they are a little on the expensive side compared to the SIM900.

      Reply
      • Hi Peter.
        You are right. Some locations no longer support 2G network. We need to shift to a 3G or 4G module soon, so that everyone in any location is able to make our projects.
        Thanks for your note.
        Regards,
        Sara 🙂

        Reply
    • Yes. You are right. We need to look for a module that supports 3G or 4G.
      Thanks for letting us know. Here, in Portugal, 2G network is still working, but there are many countries that no longer support that.

      Reply
  2. Hi Sara, I have upgraded to the SIM5216E (on an Arduino MEGA) here in Australia. With some minor software changes your projects work fine. How about adding voltage and current sensors to your SMS projects. May be reading NMEA messages as well – just a thought.

    Reply
    • Hi Arif.
      If you’re using a similar shield, the recommended power is: 5V up to 2A, or 9V 1A, or 12V 1A.
      You should check with your supplier, or test it yourself.
      Regards,
      Sara 🙂

      Reply
  3. Iam trying to make this project full wireless but the problem is that in market the battery 9v 1 amp battery is not available the battery that is available is 9v 600mah can u give any suggestions ?

    Reply
  4. Hello I have completed this project and it works very fine but i want to add pressure sensor BMP180 to it too can u guide me to which pins i can add BMP180 ?

    Reply
  5. Hi How can i make this work with Fingerprint Authentication?
    Since i have a project which is a Vault with fingerprint scanner and a temp humid sensor.
    I dont know how to work with two sensor on loop together

    Reply
    • Hi Gilbert. I don’t think so. An int stores a 16-bit value. This yields a range of -32,768 to 32,767. So, it is not appropriate to store an SMS number.
      Instead, I recommend using a char variable.
      Regards,
      Sara 🙂

      Reply
      • For example I would like to send a number(let’s say 40) via sms. Is there a way I can store this number in an integer variable?
        I would like to use that number in an if condition.. For example: if value<30 (where value is the integer variable)

        Reply
        • Hi again.
          When the arduino receives data from an SMS, it stores it in a char variable.
          Take a look at this link and see if you are able to convert the char to an int number: forum.arduino.cc/index.php?topic=103511.0
          Regards,
          Sara 🙂

          Reply
          • Hi there Sara, you said the number will be stored in char variable… Can it be used in an if function; for example if value<30 (where value is the char variable)?

          • Hi Gilbert.
            You can’t compare a char with a number.
            You should convert the char to a number first. You can use the atoi() function to convert.
            Regards,
            Sara

    • Hi.
      You don’t need to install any library for the SIM900. It communicates via serial. In the code we use the softwareserial library that is installed by default.
      Regards,
      Sara 🙂

      Reply
  6. Gsm sim 900 is stackable to arduino so is it possible to attach the sim 900 shield above the arduino board and skip the adaptor source

    Reply
  7. You can stack the SIM900 module and Arduino. I have done that myself.
    The SIM900 module needs a lot of power when transmitting.
    You only need 1 power supply. Mine is connected to the Arduino.

    Reply
    • Hi Keith.
      I haven’t experimented with SIM800 yet. So, I’m don’t know how to do that.
      Try searching for “SIM800 wiring Arduino”.
      Regards,
      Sara

      Reply
  8. bonjour j’ai essayer de le faire mais je n’arrive pas Ă  recevoir les donnĂ©es via sms.et j’ai essayer d’envoyer un simple sms mais sa marcher toujours pas

    Reply
  9. 1)Can we use this code for sim800c & lm35 temperature sensor
    2) can we change the keyword STATE to TEMPERATURE

    Reply
    • Hi.
      We don’t have any tutorials about the SIM800.
      Yes, you can change the keyword to TEMPERATURE.
      Regards,
      Sara

      Reply
  10. Bonjour a tous ,je veux poser ma question a sara ,juste savoir comment on peux envoyer le donnes lue par deux capteur differents et comment programmer le moniteur serie avec le baud

    Reply
  11. Hi I’m using the GSM 900 SHIELD installed directly on the Arduino …… g how can it work with this code please help

    Reply
  12. hi, im using sim900 and ultrasonik sensor and ds3231 built in temp sensor, when i tried to make it send a sensor value using the smsrequest code, it doesnt work, the sim recieved my message but it wont send an sms to my phone? help please thanks

    Reply
  13. Como poderia fazer para ele enviar mensagem sempre que a temperatura fosse maior que 27. enviar automatico sempre que a temperatura passar 27 e enviar para mais de 1 numero

    Reply
    • Hi Guilherme.
      W’re working on that project at the moment. So, it will be released soon: next week or the other week.
      Regards,
      Sara

      Reply
  14. hello good afternoon, did you manage to send message whenever it exceeds a certain temperature? and for more than 1 number

    thank you very much for the help, awesome project congratulations

    Reply
  15. hello
    thank for all
    Sara Santons
    why my gsm not transmit data ( when i send sms on & off good ) but not response for (state sms)

    Reply
    • Hi.
      I don’t know why you’re getting that issue.
      The SIM card must have a plan that enables it to send SMS. If the SIM card is not charged with some prepaid plan or some money, it may not be able to send the SMS.
      Regards,
      Sara

      Reply
  16. Hi, Sara,

    I’m trying to complete this project, scheme looks connect good, I took code from page (phone number changed to my number). But I dont get message back.
    Can you advise where to look for the problem?

    Reply
    • Hello. i have the same problem too.
      I wanted to ask her if she managed to solve the problem that she does not receive sms.
      I haven’t been able to yet

      Reply
  17. Thanks for this great example of code. It helps a beginner a lot! I stumbled upon 2 small issues when I tried to use your code with DFRobot’s 7600CE module.

    this line: “SIM900.println(“AT + CMGS = \”+XXXXXXXXXX\””);”
    This AT command is chopped up with spaces and 7600CE module did not accept this. Took a long while to figure this out.
    The Incomingchar also listens on outgoing SMS. Is there a way to stop it from doing this?

    Reply
  18. Thanks for the code. But when I send “STATE” to the GSM module the sensor data appears on my serial monitor instead of sending it to recepient’s number. The simcard that is inserted has a prepaid plan registered on it. Can you help me on this one?

    Im using SIM800C gsm/gprs module

    Reply
  19. I want to use this kind of project for heartbeat sensor so instead on sending STATE how can we change it so that it can send an automatic message if the sensor detects heartbeat.

    Reply
  20. Hello Sara!
    Thanks for a nice project very useful.
    My question is if I change sensor DHT to sensor DS18b20.
    What does the code look like when I change sensors

    Reply
  21. Thanks for this project, i worked on it and it works. I made changes to this line “SIM900.println(“AT + CMGS = \”+XXXXXXXXXX\””);” by removing the spaces and got the sms response.

    Reply
  22. great read.

    Can an analog signal read from any input pin of Arduino be able to be sent on request through GSM or it must always be from a specific sensor?

    Reply
  23. I am trying to compile your request for data tutorial but it showing compilation error at the if (SMSRequest()) side saying it was not declared.

    I will like to send the data to multiple recipients

    Reply

Leave a Comment

Download Our Free eBooks and Resources

Get instant access to our FREE eBooks, Resources, and Exclusive Electronics Projects by entering your email address below.