Posts with «sim900» label

Tutorial – Arduino and SIM900 GSM Modules

Use the SIM900 GSM modules with Arduino in Chapter 55 of our Arduino Tutorials. The first chapter is here, the complete series is detailed here. Updated 14/02/2014

Introduction

The goal of this tutorial is to illustrate various methods of interaction between an Arduino Uno (or compatible) and the GSM cellular network using a SIM900 GSM shield, with which you can then use your existing knowledge to build upon those methods. Updated 08/01/2014.

Apart from setting up the shield we’ll examine:

  • Making a telephone call from your Arduino
  • Sending an SMS text message
  • Receiving text messages with the shield and displaying them on the serial monitor
  • Simple controlling of the host Arduino by calling it from another telephone
  • Controlling the Arduino via SMS text message

We’ll be using a SIMCOM SIM900 GSM module shield. (If you’re looking for tutorials on the Spreadtrum SM5100 modules, start here). There must be scores of Arduino shields or modules using the SIM900, so as you can imagine each one may be a little bit different with regards to the hardware side of things – so we’re assuming you have an understanding of how hardware and software serial works as well as supply voltages and the hardware side of the Arduino world.

As for the specific shield to use, we just chose the cheapest one available at the time – which turned out to be the “SIM900 GPRS/GSM Arduino shield” from tronixlabs.com:

However with a little research and work on your part, the sketches provided should also work with any SIM900 module/shield and Arduino – as long as you have the appropriate serial and power settings.

Getting Started

A little preparation goes a long way, so make sure you’ve covered the following points:

  • Regarding your cellular provider. Do you have coverage on a GSM 850 MHz, GSM 900 MHz, DCS 1800 MHz or PCS 1900 MHz network?  When we say GSM that means 2G – not 3G, 4G or LTE. Will they allow the use of non-supported devices on the network? Some carriers will block IMEI numbers that were not provided by their sales channel. Or you may have to call the provider and supply the IMEI of your GSM module to allow it on the network. Finally, it would be wise to use either a prepaid or an account that offers unlimited SMS text messaging – you don’t want any large bills if things go wrong.
  • Power. Do you have adequate power for your SIM900 module? Some shields will use more current than the Arduino can supply (up to 2A), so you may need an external high-current supply. The Linksprite shield we use needs 5V up to 2A into the onboard DC socket. Otherwise, check with your supplier.
  • Antenna. If your module/shield etc. doesn’t have an antenna – get one. You do need it.
  • Turn off the PIN lock on the SIM card. The easiest way to do this is to put the SIM in a handset and use the menu function.
  • And as always, please don’t make an auto-dialler…

Furthermore, download the SIM900 hardware manual (.pdf) and the AT command manual (.pdf), as we’ll refer to those throughout the tutorial.

Power

There is a DC socket on the shield, which is for a 5V power supply:

Although the data from Linksprite claims the shield will use no more than 450 mA, the SIMCOM hardware manual (page 22) for the module notes that it can draw up to 2A for short bursts. So get yourself a 5V 2A power supply and connect it via the DC socket, and also ensure the switch next to the socket is set to “EXT”.

Furthermore, you can turn the GSM module on and off with the power button on the side of the shield, and it defaults to off during an initial power-up. Therefore you’ll need to set D9 to HIGH for one second in your sketch to turn the module on (or off if required for power-saving). Don’t panic, we’ll show how this is done in the sketches below.

Software Serial

We will use the Arduino software serial library in this tutorial, and the Linksprite shield has hard-wired the serial from the SIM900 to a set of jumpers, and uses a default speed of 19200. Make sure you your jumpers are set to the “SWserial” side, as shown below:

And thus whenever an instance of SoftwareSerial is created, we use 7,8 as shown below:

SoftwareSerial SIM900(7, 8); // RX, TX

If you shield is different, you’ll need to change the TX and RX pin numbers. This also means you can’t use an Arduino Leonardo or Mega (easily). Finally – note this for later – if your shield is having problems sending data back to your Arduino you may need to edit the SoftwareSerial library – read this for more information.

Wow – all those rules and warnings?

The sections above may sound a little authoritarian, however we want your project to be a success. Now, let’s get started…

A quick test…

At this point we’ll check to make sure your shield and locate and connect to the cellular network. So make sure your SIM card is active with your cellular provider, the PIN lock is off, and then insert it and lock the SIM card  to the carrier on the bottom of the shield:

Then plug the shield into your Uno, attach 5V power to the DC socked on the GSM shield, and USB from the Uno to the PC. Press the “PWRKEY” button on the side of the shield for a second, then watch the following two LEDs:

The bright “STATUS” LED will come on, and then the “NETLIGHT” LED will blink once every 800 milliseconds- until the GSM module has found the network, at which point it will blink once every three seconds. This is shown in the following video:

Nothing can happen until that magic three-second blink – so if that doesn’t appear after a minute, something is wrong. Check your shield has the appropriate power supply, the antenna is connected correctly, the SIM card is seated properly and locked in- and that your cellular account is in order. Finally, you may not have reception in that particular area, so check using a phone on the same network or move to a different location.

Making a telephone call from your Arduino

You can have your Arduino call a telephone number, wait a moment – then hang up. This is an inexpensive way of alerting you of and consider the following sketch:

// Example 55.1

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8); // configure software serial port

void setup()
{
  SIM900.begin(19200);               
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void callSomeone()
{
  SIM900.println("ATD + +12128675309;"); // dial US (212) 8675309
  delay(100);
  SIM900.println();
  delay(30000);            // wait for 30 seconds...
  SIM900.println("ATH");   // hang up
}

void loop()
{
  callSomeone(); // call someone
  SIM900power();   // power off GSM shield
  do {} while (1); // do nothing
}

The sketch first creates a software serial port, then in void setup() starts the software serial port, and also turns on the GSM shield with the function SIM900power (which simply sets D9 high for a second which is the equivalent of pressing the power button). Notice the delay function in void setup – this gives the GSM module a period of time to locate and log on to the cellular network. You may need to increase (or be able to decrease) the delay value depending on your particular situation. If in doubt, leave it as a long period.

The process of actually making the call is in the function callSomeone(). It sends a string of text to the GSM module which consists of an AT command. These are considered the “language” for modems and thus used for various tasks. We use the ATD command to dial (AT… D for dial) a number. The number as you can see in the sketch needs to be in world-format. So that’s a “+” then the country code, then the phone number with area code (without the preceding zero).

So if your number to call is Australia (02) 92679111 you would enter +61292679111. Etcetera. A carriage return is then sent to finalise the command and off it goes dialling the number. Here’s a quick video demonstration for the non-believers:

After thirty seconds we instruct the module to hand up with another AT command – “ATH” (AT… H for “hang up”), followed by turning off the power to the module. By separating the call feature into a function – you can now insert this into a sketch (plus the preceding setup code) to call a number when required.

Sending an SMS text message

This is a great way of getting data from your Arduino to almost any mobile phone in the world, at a very low cost. For reference, the maximum length of an SMS text message is 160 characters – however you can still say a lot with that size limit. First we’ll demonstrate sending an arbitrary SMS. Consider the following sketch:

// Example 55.2

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void sendSMS()
{
  SIM900.print("AT+CMGF=1\r");                                                        // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");                                     // recipient's mobile number, in international format
  delay(100);
  SIM900.println("Hello, world. This is a text message from an Arduino Uno.");        // message to send
  delay(100);
  SIM900.println((char)26);                       // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  sendSMS();
  do {} while (1);
}

The basic structure and setup functions of the sketch are the same as the previous example, however the difference here is the function sendSMS(). It used the AT command “AT+CMGF” to tell the GSM module we want to send an SMS in text form, and then “AT+CMGS” followed by the recipient’s number. Once again note the number is in international format. After sending the send SMS commands, the module needs  five seconds to do this before we can switch it off. And now for our ubiquitous demonstration video:

 

You can also send text messages that are comprised of numerical data and so on – by compiling the required text and data into a string, and then sending that. Doing so gives you a method to send such information as sensor data or other parameters by text message.

For example, you might want to send daily temperature reports or hourly water tank levels. For our example, we’ll demonstrate how to send a couple of random numbers and some text as an SMS. You can then use this as a framework for your own requirements. Consider the following sketch:

// Example 55.3

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int x,y;
String textForSMS;

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
  randomSeed(analogRead(0));
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void sendSMS(String message)
{
  SIM900.print("AT+CMGF=1\r");                     // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");  // recipient's mobile number, in international format
  delay(100);
  SIM900.println(message);                         // message to send
  delay(100);
  SIM900.println((char)26);                        // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  x = random(0,255);
  y = random(0,255);
  textForSMS = "Your random numbers are ";
  textForSMS.concat(x);
  textForSMS = textForSMS + " and ";
  textForSMS.concat(y);
  textForSMS = textForSMS + ". Enjoy!";  
  sendSMS(textForSMS);
  do {} while (1);
}

Take note of the changes to the function sendSMS(). It now has a parameter – message, which is a String which contains the text to send as an SMS. In void loop() the string variable textForSMS is constructed. First it contains some text, then the values for x and y are added with some more text. Finally the string is passed to be sent as an SMS. And here it is in action:

Receiving text messages and displaying them on the serial monitor 

Now let’s examine receiving text messages. All we need is to send two AT commands inside void setup() and then repeat every character sent from the shield to the serial monitor. The first command to use is AT+CMGF=1  which sets the SMS mode to text (as used in the previous example) and the second is AT+CNMI=2,2,0,0 – which tells the GSM module to send the contents of any new SMS out to the serial line. To demonstrate this, set up your hardware as before, upload the following sketch:

// Example 55.4

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

char incoming_char=0;

void setup()
{
  Serial.begin(19200); // for serial monitor
  SIM900.begin(19200); // for GSM shield
  SIM900power();  // turn on shield
  delay(20000);  // give time to log on to network.

  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r"); 
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop()
{
  // Now we simply display any text that the GSM shield sends out on the serial monitor
  if(SIM900.available() >0)
  {
    incoming_char=SIM900.read(); //Get the character from the cellular serial port.
    Serial.print(incoming_char); //Print the incoming character to the terminal.
  }
}

… then open the serial monitor, check it’s set to 19200 bps and wait around thirty seconds. You will see some odd characters, then the “OK” responses from the GSM module. Now send a text message to the shield – the time/date stamp, sender and message will appear, for example:

To preserve my sanity the number used in the demonstrations will be blanked out.

Simple controlling of the host Arduino by calling it from another telephone

When we call our shield from another telephone, it sends the text “RING” out to serial, then “NO CARRIER” when you hang up – which can be harnessed to create a simple dial-in remote control. Use the sketch from the previous example to test this – for example:

You can also display the number calling in by using the AT command AT+CLIP=1. To do this, just add the following lines to void setup() in the previous sketch:

SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
delay(100);

Now when a call is received, the caller’s number appears as well – for example:

Note that the caller ID data for incoming calls isn’t in the international format as it was with SMSs. This will vary depending on your country, so check it out for yourself.

So how can we control the Arduino by calling in? By counting the number of times the shield sends “RING” to the Arduino (just as we did with the other GSM shield). To do this we simply count the number of times the word “RING” comes in from the shield, and then after the third ring – the Arduino will do something.

For our example we have two LEDs connected (via 560Ω resistors) to D12 and D13. When we call the shield and let it ring three times, they will alternate between on and off. Enter and upload the following sketch:

// Example 55.5

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int numring=0;
int comring=3; 
int onoff=0; // 0 = off, 1 = on

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT); // LEDs - off = red, on = green
  digitalWrite(12, HIGH);
  digitalWrite(13, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
  delay(100);  
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void doSomething()
{
  if (onoff==0)
  {
    onoff=1;
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    Serial.println("D12 high D13 low");
  } 
  else
    if (onoff==1)
    {
      onoff=0;
      digitalWrite(12, LOW);
      digitalWrite(13, HIGH);
      Serial.println("D12 low D13 high");
    }
}

void loop() 
{
  if(SIM900.available() >0)
  {
    inchar=SIM900.read(); 
    if (inchar=='R')
    {
      delay(10);
      inchar=SIM900.read(); 
      if (inchar=='I')
      {
        delay(10);
        inchar=SIM900.read();
        if (inchar=='N')
        {
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='G')
          {
            delay(10);
            // So the phone (our GSM shield) has 'rung' once, i.e. if it were a real phone
            // it would have sounded 'ring-ring' or 'blurrrrr' or whatever one cycle of your ring tone is
            numring++;
            Serial.println("ring!");
            if (numring==comring)
            {
              numring=0; // reset ring counter
              doSomething();
            }
          }
        }
      }
    }
  }
}

You can change the number of rings before action with the variable comring, and the action to take is in the function void doSomething(). Finally you can watch a short video of this in action.


We can also modify this system so it only allows control by callers from one number  –  as long as caller ID works on your system (well it should… it’s 2014 not 1996). So in the next example the system will only call the function doSomething if the call is from a certain number. The sketch works in the same manner as last time – but instead of counting the word “RING”, it will compare the incoming caller’s ID number against one in the sketch.

It may look a little clunky, but it works. In the following example sketch, the number is 2128675309 – so just change the digits to check in void loop():

// Example 55.6

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int onoff=0; // 0 = off, 1 = on

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(12, OUTPUT);
  pinMode(13, OUTPUT); // LEDs - off = red, on = green
  digitalWrite(12, HIGH);
  digitalWrite(13, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  delay(20000);  // give time to log on to network.
  SIM900.print("AT+CLIP=1\r"); // turn on caller ID notification
  delay(100);  
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void doSomething()
{
  if (onoff==0)
  {
    onoff=1;
    digitalWrite(12, HIGH);
    digitalWrite(13, LOW);
    Serial.println("D12 high D13 low");
  } 
  else
    if (onoff==1)
    {
      onoff=0;
      digitalWrite(12, LOW);
      digitalWrite(13, HIGH);
      Serial.println("D12 low D13 high");
    }
}

void loop() 
{
  if(SIM900.available() >0)
  {   
    inchar=SIM900.read(); 
    if (inchar=='2')
    {
      delay(10);
      inchar=SIM900.read(); 
      if (inchar=='1')
      {
        delay(10);
        inchar=SIM900.read(); 
        if (inchar=='2')
        {
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='8')
          {
            delay(10);
            inchar=SIM900.read(); 
            if (inchar=='6')
            {
              delay(10);
              inchar=SIM900.read(); 
              if (inchar=='7')
              {
                delay(10);
                inchar=SIM900.read(); 
                if (inchar=='5')
                {
                  delay(10);
                  inchar=SIM900.read(); 
                  if (inchar=='3')
                  {
                    delay(10);
                    inchar=SIM900.read();
                    if (inchar=='0')
                    {
                      delay(10);
                      inchar=SIM900.read(); 
                      if (inchar=='9')
                      {
                        Serial.println("do sometehing");
                        delay(10);
                        // now the number is matched, do something
                        doSomething();
                        // arbitrary delay so the function isn't called again on the same phone call
                        delay(60000);
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

The large delay after calling doSomething() exists to stop the same action being called twice (or more) on the same inbound call. Anyhow, you should now have a grasp on interrogating the data from the shield. Which leads us to the final section…

Controlling the Arduino via SMS text message

As you did with the caller ID data, you can also control the Arduino via SMS fairly easily, and have more options. In our example we’ll explain how to control four digital output pins via SMS. The example works in two stages. First it will wait for an SMS to be received, and then have the contents sent to the Arduino via serial just as we did earlier with the example 55.4. The next stage is to filter out the commands in the text message as we did with example 55.6.

The commands (that is, the contents of your text message to the Arduino) will be in the form

#axbxcxdx

where ‘x’ will be 0 (for off) and 1 (for on) – and a, b, c and d will relate to digital pins 10, 11, 12 and 13. For example, to turn on D10, 11 and turn off D12, D13 you would compose your SMS as #a1b1c0d0. After processing the SMS we use the AT command AT+CMGD=1,4 to delete all the SMSs from the SIM card, otherwise it will fill up and reject further commands. Moving on, here’s the example sketch:

// Example 55.7

#include <SoftwareSerial.h> 
char inchar; // Will hold the incoming character from the GSM shield
SoftwareSerial SIM900(7, 8);

int led1 = 10;
int led2 = 11;
int led3 = 12;
int led4 = 13;

void setup()
{
  Serial.begin(19200);
  // set up the digital pins to control
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);
  pinMode(led3, OUTPUT);
  pinMode(led4, OUTPUT);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  digitalWrite(led3, LOW);
  digitalWrite(led4, LOW);

  // wake up the GSM shield
  SIM900power(); 
  SIM900.begin(19200);
  delay(20000);  // give time to log on to network.
  SIM900.print("AT+CMGF=1\r");  // set SMS mode to text
  delay(100);
  SIM900.print("AT+CNMI=2,2,0,0,0\r"); 
  // blurt out contents of new SMS upon receipt to the GSM shield's serial out
  delay(100);
  Serial.println("Ready...");
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void loop() 
{
  //If a character comes in from the cellular module...
  if(SIM900.available() >0)
  {
    inchar=SIM900.read(); 
    if (inchar=='#')
    {
      delay(10);

      inchar=SIM900.read(); 
      if (inchar=='a')
      {
        delay(10);
        inchar=SIM900.read();
        if (inchar=='0')
        {
          digitalWrite(led1, LOW);
        } 
        else if (inchar=='1')
        {
          digitalWrite(led1, HIGH);
        }
        delay(10);
        inchar=SIM900.read(); 
        if (inchar=='b')
        {
          inchar=SIM900.read();
          if (inchar=='0')
          {
            digitalWrite(led2, LOW);
          } 
          else if (inchar=='1')
          {
            digitalWrite(led2, HIGH);
          }
          delay(10);
          inchar=SIM900.read(); 
          if (inchar=='c')
          {
            inchar=SIM900.read();
            if (inchar=='0')
            {
              digitalWrite(led3, LOW);
            } 
            else if (inchar=='1')
            {
              digitalWrite(led3, HIGH);
            }
            delay(10);
            inchar=SIM900.read(); 
            if (inchar=='d')
            {
              delay(10);
              inchar=SIM900.read();
              if (inchar=='0')
              {
                digitalWrite(led4, LOW);
              } 
              else if (inchar=='1')
              {
                digitalWrite(led4, HIGH);
              }
              delay(10);
            }
          }
          SIM900.println("AT+CMGD=1,4"); // delete all SMS
        }
      }
    }
  }
}

The example hardware has four LEDs via 560Ω resistors on the digital outputs being controlled. Finally, you can watch a short demonstration in this video.

Conclusion

After working through this tutorial you should have an understanding of how to use the SIM900 GSM shields to communicate and control with an Arduino. And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop”.

Have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column, or join our forum – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Tutorial – Arduino and SIM900 GSM Modules appeared first on tronixstuff.

Tutorial – Arduino and SIM900 GSM Modules

Use the SIM900 GSM modules with Arduino in Chapter 55 of our Arduino Tutorials. The first chapter is here, the complete series is detailed here.

Introduction

The goal of this tutorial is to illustrate various methods of interaction between an Arduino Uno (or compatible) and the GSM cellular network using a SIM900 GSM shield, with which you can then use your existing knowledge to build upon those methods.

We’ll be using a SIMCOM SIM900 GSM module shield. (If you’re looking for tutorials on the Spreadtrum SM5100 modules, start here). There must be scores of Arduino shields or modules using the SIM900, so as you can imagine each one may be a little bit different with regards to the hardware side of things – so we’re assuming you have an understanding of how hardware and software serial works as well as supply voltages and the hardware side of the Arduino world.

As for the specific shield to use, we just chose the cheapest one available at the time – which turned out to be the “SIM900 GPRS/GSM Arduino shield” from Linksprite:

However with a little research and work, the sketches provided should also work with any SIM900 module/shield and Arduino – as long as you have the appropriate serial and power settings. 

Getting Started

A little preparation goes a long way, so make sure you’ve covered the following points:

  • Regarding your cellular provider. Do you have coverage on a GSM 850 MHz, GSM 900 MHz, DCS 1800 MHz or PCS 1900 MHz network?  When we say GSM that means 2G – not 3G, 4G or LTE. Will they allow the use of non-supported devices on the network? Some carriers will block IMEI numbers that were not provided by their sales channel. Or you may have to call the provider and supply the IMEI of your GSM module to allow it on the network. Finally, it would be wise to use either a prepaid or an account that offers unlimited SMS text messaging – you don’t want any large bills if things go wrong.
  • Power. Do you have adequate power for your SIM900 module? Some shields will use more current than the Arduino can supply (up to 2A), so you may need an external high-current supply. The Linksprite shield we use needs 5V up to 2A into the onboard DC socket. Otherwise, check with your supplier.
  • Antenna. If your module/shield etc. doesn’t have an antenna – get one. You do need it.
  • Turn off the PIN lock on the SIM card. The easiest way to do this is to put the SIM in a handset and use the menu function.
  • And as always, please don’t make an auto-dialler…

Furthermore, download the SIM900 hardware manual (.pdf) and the AT command manual (.pdf), as we’ll refer to those throughout the tutorial.

Power

There is a DC socket on the shield, which is for a 5V power supply:

Although the data from Linksprite claims the shield will use no more than 450 mA, the SIMCOM hardware manual (page 22) for the module notes that it can draw up to 2A for short bursts. So get yourself a 5V 2A power supply and connect it via the DC socket, and also ensure the switch next to the socket is set to “EXT”.

Furthermore, you can turn the GSM module on and off with the power button on the side of the shield, and it defaults to off during an initial power-up. Therefore you’ll need to set D9 to HIGH for one second in your sketch to turn the module on (or off if required for power-saving). Don’t panic, we’ll show how this is done in the sketches below.

Software Serial

We will use the Arduino software serial library in this tutorial, and the Linksprite shield has hard-wired the serial from the SIM900 to a set of jumpers, and uses a default speed of 19200. Make sure you your jumpers are set to the “SWserial” side, as shown below:

And thus whenever an instance of SoftwareSerial is created, we use 7,8 as shown below:

SoftwareSerial SIM900(7, 8); // RX, TX

If you shield is different, you’ll need to change the TX and RX pin numbers. This also means you can’t use an Arduino Leonardo or Mega (easily).

Wow – all those rules and warnings?

The sections above may sound a little authoritarian, however we want your project to be a success. Now, let’s get started…

A quick test…

At this point we’ll check to make sure your shield and locate and connect to the cellular network. So make sure your SIM card is active with your cellular provider, the PIN lock is off, and then insert it and lock the SIM card  to the carrier on the bottom of the shield:

Then plug the shield into your Uno, attach 5V power to the DC socked on the GSM shield, and USB from the Uno to the PC. Press the “PWRKEY” button on the side of the shield for a second, then watch the following two LEDs:

The bright “STATUS” LED will come on, and then the “NETLIGHT” LED will blink once every 800 milliseconds- until the GSM module has found the network, at which point it will blink once every three seconds. This is shown in the following video:

Nothing can happen until that magic three-second blink – so if that doesn’t appear after a minute, something is wrong. Check your shield has the appropriate power supply, the antenna is connected correctly, the SIM card is seated properly and locked in- and that your cellular account is in order. Finally, you may not have reception in that particular area, so check using a phone on the same network or move to a different location.

Making a telephone call from your Arduino

You can have your Arduino call a telephone number, wait a moment – then hang up. This is an inexpensive way of alerting you of and consider the following sketch:

// Example 55.1

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8); // configure software serial port

void setup()
{
  SIM900.begin(19200);               
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void callSomeone()
{
  SIM900.println("ATD + +12128675309;"); // dial US (212) 8675309
  delay(100);
  SIM900.println();
  delay(30000);            // wait for 30 seconds...
  SIM900.println("ATH");   // hang up
}

void loop()
{
  callSomeone(); // call someone
  SIM900power();   // power off GSM shield
  do {} while (1); // do nothing
}

The sketch first creates a software serial port, then in void setup() starts the software serial port, and also turns on the GSM shield with the function SIM900power (which simply sets D9 high for a second which is the equivalent of pressing the power button). Notice the delay function in void setup – this gives the GSM module a period of time to locate and log on to the cellular network. You may need to increase (or be able to decrease) the delay value depending on your particular situation. If in doubt, leave it as a long period.

The process of actually making the call is in the function callSomeone(). It sends a string of text to the GSM module which consists of an AT command. These are considered the “language” for modems and thus used for various tasks. We use the ATD command to dial (AT… D for dial) a number. The number as you can see in the sketch needs to be in world-format. So that’s a “+” then the country code, then the phone number with area code (without the preceding zero).

So if your number to call is Australia (02) 92679111 you would enter +61292679111. Etcetera. A carriage return is then sent to finalise the command and off it goes dialling the number. Here’s a quick video demonstration for the non-believers:

After thirty seconds we instruct the module to hand up with another AT command – “ATH” (AT… H for “hang up”), followed by turning off the power to the module. By separating the call feature into a function – you can now insert this into a sketch (plus the preceding setup code) to call a number when required.

Sending an SMS text message

This is a great way of getting data from your Arduino to almost any mobile phone in the world, at a very low cost. For reference, the maximum length of an SMS text message is 160 characters – however you can still say a lot with that size limit. First we’ll demonstrate sending an arbitrary SMS. Consider the following sketch:

// Example 55.2

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(5000);
}

void sendSMS()
{
  SIM900.print("AT+CMGF=1\r");                                                        // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");                                     // recipient's mobile number, in international format
  delay(100);
  SIM900.println("Hello, world. This is a text message from an Arduino Uno.");        // message to send
  delay(100);
  SIM900.println((char)26);                       // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  sendSMS();
  do {} while (1);
}

The basic structure and setup functions of the sketch are the same as the previous example, however the difference here is the function sendSMS(). It used the AT command “AT+CMGF” to tell the GSM module we want to send an SMS in text form, and then “AT+CMGS” followed by the recipient’s number. Once again note the number is in international format. After sending the send SMS commands, the module needs  five seconds to do this before we can switch it off. And now for our ubiquitous demonstration video:

 

You can also send text messages that are comprised of numerical data and so on – by compiling the required text and data into a string, and then sending that. Doing so gives you a method to send such information as sensor data or other parameters by text message.

For example, you might want to send daily temperature reports or hourly water tank levels. For our example, we’ll demonstrate how to send a couple of random numbers and some text as an SMS. You can then use this as a framework for your own requirements. Consider the following sketch:

// Example 55.3

#include <SoftwareSerial.h>
SoftwareSerial SIM900(7, 8);
int x,y;
String textForSMS;

void setup()
{
  SIM900.begin(19200);
  SIM900power();  
  delay(20000);  // give time to log on to network. 
  randomSeed(analogRead(0));
}

void SIM900power()
// software equivalent of pressing the GSM shield "power" button
{
  digitalWrite(9, HIGH);
  delay(1000);
  digitalWrite(9, LOW);
  delay(7000);
}

void sendSMS(String message)
{
  SIM900.print("AT+CMGF=1\r");                     // AT command to send SMS message
  delay(100);
  SIM900.println("AT + CMGS = \"+12128675309\"");  // recipient's mobile number, in international format
  delay(100);
  SIM900.println(message);                         // message to send
  delay(100);
  SIM900.println((char)26);                        // End AT command with a ^Z, ASCII code 26
  delay(100); 
  SIM900.println();
  delay(5000);                                     // give module time to send SMS
  SIM900power();                                   // turn off module
}

void loop()
{
  x = random(0,255);
  y = random(0,255);
  textForSMS = "Your random numbers are ";
  textForSMS.concat(x);
  textForSMS = textForSMS + " and ";
  textForSMS.concat(y);
  textForSMS = textForSMS + ". Enjoy!";  
  sendSMS(textForSMS);
  do {} while (1);
}

Take note of the changes to the function sendSMS(). It now has a parameter – message, which is a String which contains the text to send as an SMS. In void loop() the string variable textForSMS is constructed. First it contains some text, then the values for x and y are added with some more text. Finally the string is passed to be sent as an SMS. And here it is in action:

Conclusion

After working through this tutorial you should have an understanding of how the basics of the GSM shield and AT commands work. If there’ s demand we’ll continue with more features and possibilities in a future tutorial, so let us know via the contact page.  And if you enjoyed the tutorial, or want to introduce someone else to the interesting world of Arduino – check out my book (now in a third printing!) “Arduino Workshop” from No Starch Press.

In the meanwhile have fun and keep checking into tronixstuff.com. Why not follow things on twitterGoogle+, subscribe  for email updates or RSS using the links on the right-hand column? And join our friendly Google Group – dedicated to the projects and related items on this website. Sign up – it’s free, helpful to each other –  and we can all learn something.

The post Tutorial – Arduino and SIM900 GSM Modules appeared first on tronixstuff.

Tronixstuff 18 Sep 03:33

GSM GPS shield for Arduino

-->-->-->-->

Shield for Arduino designed and based on the module GSM/GPRS SIM900 or the GSM/GPRS & GPS module SIM908, to make calls, voice and data connections via GPRS.

 

 

HARDWARE INNOVATIONS


This new version (old Arduino GSM shield) has several new hardware features, that allow maximum customization and provide many configurations.

We begin with the supply circuit a simple LM7805. To work, it is necessary to provide an input voltage between 7.5V and 12V. As shown in the circuit diagram, the input voltage, after being stabilized at 5 V, is reduced to 4.3 V by using a diode and provide power to modules that need a voltage between the 3.2 and 4.8 V. During the operations such as the use of GPRS, the module absorbs a current of about 1 A, therefore it is necessary that the power source is able to provide this current intensity.

An important technical feature is the serial adapter for the communication between the GSM module and Arduino. To reduce the tension has been used a simple voltage divider, while for raising the voltage from the GSM module to Arduino we chose a MOSFET BS170.

The news that is immediately evident is the presence of two jacks for audio. With a microphone and a headset with a 3.5 mm jack (just the standard headphones for computers), you can make a voice call

To preserve compatibility with the Arduino Mega, we changed the selection method for the serial communication. The two different serial communication modes (hardware or software) are selectable by jumper, leaving the user the choice between the two configurations ( for serial software in this new version we adopted pins 2 and 3) or possibly use the pin to your choice with a simple wire connection. With this solution you can use the Arduino Mega using two of the four serial that it has, or possibly carry out the communication through a serial software via two pins of your choice.

Always to preserve maximum flexibility and customization, there are some pins on the back of PCB, which allow to make the connections from the Arduino digital ports and the control signals data flow (CTS, RTS) or alerts for incoming calls or unread SMS (RI). In this new version, you can then disable these connections to save inputs or outputs pins.

Comparing the new card with the previous one, you can see the presence of two connectors on the top.These additional connections allow the use of the shield also with the new small breakout for SIM900 and SIM908. The new module Simcom SIM908, is characterized by the presence of a GPS with 42 channels.

The scenery offered by this new module SIMCOM, in addition to GSM GPRS shield, it is quite remarkable: the creation of a GPS tracking device that can communicate the location via the Internet (or SMS) is now available to everyone, avoiding all the problems due to assembly and low-level programming.

A further feature of this new version, concerns the presence of a supercap for circuit dedicated to the RTC (Real Time Clock). Inside the SIM900, as well as the SIM908, there is a circuit that is responsible for updating the clock even without power.

 

GSM GPS SHIELD SCHEMATICS


R1: 10 kohm
R2: 10 kohm
R3: 10 kohm
R4: 10 kohm

C1: 100 nF
C2: 470 µF 25 VL
C3: 100 nF
C4: 220 µF 16 VL
C5: 47 pF
C6: 47 pF
C7: 47 pF
C8: 47 pF
C9: 47 pF
C10: 47 pF
C11: 220 µF 16 VL
C12: 100 nF

CRCT:  0,1F

U1: 7805

T1: BS170

D1: 1N4007

P1: Microswitch

MIC: jack 3,5 mm
SPK: jack 3,5 mm

 

SOFTWARE INNOVATIONS

The software library related to the GSM GPRS shield has been updated.  The library is open-source and uses the hosting service Google Project, located at http://code.google.com/p/gsm-shield-arduino/ . The library is constantly updated and improved with the addition of new features, so please check that you always have the latest release.

The main enhancement is the TPC/IP communication support through GPRS.

With a simple function, you can connect Arduino to internet using the APN (Access Point Name) you choose. After that we will automatically get an IP address by the provider.

To establish communication you must define which device performs the function of the server (still waiting for some connection), such as that client (requires a connection to the server according to the information you want to achieve) and that leads to exchange data .

In the library there are two functions that allow us to set the device to listen on a particular port for connections (server), or to establish a connection based on the server address and port chosen (client) .

Once connected, you can send the data, which can be command strings or just the data you want to monitor, for this action there is a high-level function, which simplifies the management.

 

LIBRARY FUNCTIONS GSM GPRS

First, you must have the folder libraries, in the root directory of the Arduino, the folder GSM_GPRS containing all the functions you can use.

Now if you want to change the serial port, through the jumper, you have to modify the file GSM.cpp.

To save memory, we decided to divide the functions into different classes contained in different files, to allow you to include or not the code parts needed, thus going to save memory RAM, leaving it free for the rest of the program. For the basic operation is always necessary to include files SIM900.h and SoftwareSerial.h, while depending on the needs you may include call.h (for call handling), sms.h (for sending, receiving and saving SMS) and inetGSM.h (containing functions related to HTTP, and GPRS).

SIM900.h

You should always include this file. It contains the basic functions for starting and configuring the GSM module.  Simply call the functions using “GSM.” As a prefix.

int gsm.begin(int baudrate) Turn the power on and sets the baud rate for communication. gsm.TurnOn(9600);
void SimpleRead() Reads a byte from the serial buffer. gsm.SimpleRead();
void SimpleWrite(char* cmd) Writes the string (or an integer) on the serial port. gsm.SimpleRead(“AT+CSQ”);
char SendATCmdWaitResp (char const* AT_cmd_string, uint16_t start_comm_tmout, uint16_t max_interchar_tmout, char const* response_string,byte no_of_attempts) Sends an AT command passed as a parameter, controlling the time of timeout for the receipt of a response and between one character and another. After receiving the response, compares it with that expected, if different resends the command for the set number of times.The possible outputs are shown below, with the relative enumeration. AT_RESP_ERR_NO_RESP or -1: No response received.AT_RESP_ERR_DIF_RESP or 0: Response different from that expected.AT_RESP_OK or 1: The response contains the expected string. If (gsm.SendATCmdWaitResp (“AT”,500,50,”OK”,3)== AT_RESP_OK)
Serial.println(“OK”);

 

call.h

In case you want to make a call, or simply refuse to answer an incoming call, you must use this class. To use these functions simply instantiate the object in the sketch. The functions listed in the table below refers to an object created with the following command at the beginning of the sketch: CallGSM call;

void Call(char* number_string) Makes a call to the number contained in the string call.Call(“+393471234567”)
void PickUp(void) During an incoming call, it responds and activates the audio communication. call.PickUp();
void HangUp(void) During an active call, hang up and disables audio communication. call.HangUp();
byte CallStatus(void); Returns the state about the phone calls.The possible output byte are listed under the following names:CALL_NONE or 0: No call.CALL_INCOM_VOICE or 1: An incoming call.CALL_ACTIVE_VOICE or 2: Active Call. If (call.CallStatus()== CALL_ACTIVE_VOICE)
Serial.println(“CALL ACTIVE”);
byte CallStatusWithAuth (char* phone_number,                             byte first_authorized_pos, byte last_authorized_pos); Unlike the previous distinguish if the active call, or incoming belongs to a number stored on the SIM in a position between the start and end, passed as parameters.  The possible output byte are listed under the following names:CALL_NONE or 0: No call.CALL_INCOM_VOICE_AUTH or 3: Incoming call from a number authenticated. CALL_INCOM_VOICE_NOT_AUTH or 4: Incoming call from a number not authenticated. If (call.CallStatusWithAuth() == CALL_INCOM_VOICE_AUTH)
Serial.println (“INCOMING CALL FROM A AUTH NUMBER”);

 

SMS.h

For managing text messages must use this special class. As before, it is necessary to recall it within the sketch and then instantiate an object. For example, in the following functions refers to an object created at the beginning of the sketch, with the command SMSGSM sms;

char SendSMS(char *number_str, char *message_str) Using the following command is sent an SMS to the number contained in the first string passed as a parameter with the text in the second. sms.SendSMS (“+393471234567” , ”Hello Arduino”);
char SendSMS(byte sim_phonebook_position, char *message_str) Send an SMS as before, where instead of the string is passed to the recipient’s contact position stored on the SIM. sms.SendSMS(1,”Hello Arduino”);
char GetSMS(byte position, char *phone_number, char *SMS_text, byte max_SMS_len) Reads the SMS stored on the SIM in the position passed as a parameter, saving the sender’s number in the first string passed in the second and the content of specified length. char number[13];
char text[200];
sms.GetSMS(1,number,text,200);

 

inetGSM.h

In this class are included functions to connect and manage communications via HTTP protocol. In the following examples was an object created with the command InetGSM inet;

int httpGET(const char* server, int port, const char* path, char* result, int resultlength) Send a GET request to the specified server on the specified port, requiring a certain path and saving the response to a string of the specified length. Returns the number of bytes read. char text[200];
inet.httpGET (“www.open-electronics.org”, 80,”/”,text,200);
int httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength) Send a POST request to the specified server on the specified port, requiring a certain path, passing the parameters set and saving the response string of the specified length. Returns the number of bytes read. char text[200];
inet.httpGET (“www.open-electronics.org”, 80,”/”,text,200);
int attachGPRS(char* domain, char* dom1, char* dom2) Initiates the connection using the GPRS APN passed as the first parameter.  The second and third arguments are two strings that contain the username and password. If no authentication is required, just pass the last two strings empty. inet.attachGPRS (“internet.wind”,””,””);
int deattachGPRS(void) Disconnects the module from the GPRS network. inet.deattachGPRS();
int connectTCP(const char* server, int port) Establishes a connection as a client to the server passed as a parameter on the port defined by the second parameter. inet.connectTCP (“www.open-electronics.org”, 80);
int disconnectTCP(void) Closes the communication with the server. inet.disconnectTCP();
int connectTCPServer(int port) Puts the module listens on the specified port waiting for a connection from a client. inet.connectTCPServer(80);
boolean connectedClient(void) Returns true if a client is connected to the module, otherwise false. inet.connectedClient();

 

EXAMPLE FOR CALLS AND SMS WITH THE GSM GPRS SHIELD 

Let us now, step by step, our first sketch to use the shield using the Arduino IDE version 1.00. We will write a program that when it receives a call from a preset number (stored in a specific location on the SIM), rejects the call and sends an SMS in response to the caller with the value read from an input.

First you have to extract the files from the compressed folder within the Library folder libraries contained within the installation folder of Arduino.

To first load the libraries using the following commands

#include “SIM900.h”

#include <SoftwareSerial.h>

Then load, uncomment properly, the files related to classes containing functions that we want to use for the management of phone calls and SMS.

#include “sms.h”

#include “call.h”

We will perform the initialization procedure in the setup. Set the pin to read the value which will then be sent via SMS, configure the serial communication and initialize the module with the function gsm.begin, and set the baud rate (usually for proper communication of data through GPRS is advisable not rise above 4800 baud).

At this point we enter the heart of the program, which will periodically check the status of incoming calls. To do this within the cycle loop will use the function call.CallStatusWithAuth saving the byte returned. In the case of incoming or in progress call, the sender (or recipient) number is stored in the string number.

Compared with the value stored CALL_INCOM_VOICE_AUTH, which describes an incoming call by a number in that set, we reject the call using the GSM.Hangup and after waiting 2 seconds, read the input value and send the message.The value read is an integer and must be first converted into a string using the function itoa.

Let us remember to insert a delay, inside the loop function, to ensure that the module is interrogated at intervals of not less than a second. Commands sent in rapid sequence could corrupt the stability of the module.

If we do not receive the result of proper initialization, you will need to check the power supply. Remember that it is recommended to use an external power source because the only power supplied by the USB port is not enought.

If the power is found to be correct, you should check that the file GSM.cpp, in the library are declared properly pin for the serial. Basically the new version uses pins 2 and 3, while the old version used pins 4 and 5.

#define _GSM_TXPIN_ 2

#define _GSM_RXPIN_ 3

The full program is as follows:

#include "SIM900.h"
#include <SoftwareSerial.h>
//carichiamo i file necessari allo sketch
#include "sms.h"
#include "call.h"

CallGSM call;            
SMSGSM sms;              

char number[20];
byte stat=0;
int value=0;
int pin=1;
char value_str[5];

void setup()
{
  pinMode(pin,INPUT);
  Serial.begin(9600);
  Serial.println("GSM GPRS Shield");
  //init the module
  if (gsm.begin(2400))
    Serial.println("\nstatus=READY");
  else Serial.println("\nstatus=IDLE");
};

void loop()
{
  stat=call.CallStatusWithAuth(number,1,3);
  if(stat==CALL_INCOM_VOICE_AUTH){
    call.HangUp();
    delay(2000);
    value=digitalRead(1);
    itoa(value,value_str,10);
    sms.SendSMS(number,value_str);
  }
  delay(1000);
};

 

EXAMPLE FOR INTERNET

We analyze one of the examples contained within the library to connect Arduino to the internet with GPRS connection.

We will make a program capable of receiving HTML content from a web page and save the first 50 characters.

Because we use only the functions relating to the Internet and HTTP, we load in addition to the standard library file, the file inetGSM.h

Instantiate an object management functions

InetGSM inet;

and as before we execute the initialization routine. Then we establish a GPRS connection. In this step you need to run the command “AT+CIFSR” that requires the provider the IP address assigned to the GSM module. This step is important. Some providers garantee the connection only if previously it’s made this request. Through the function gsm.WhileSimpleRead contained in the GSM class, we read the entire contents of the buffer. Once emptied the buffer, the sketch will go to the following functions.

At this point we are connected, we have to establish a TCP connection with the server, send a GET request to a web page and store the contents of the response in a previously declared array. All this is done by the function HttpGet in class inetGSM. In addition to the server and port (80 in the case of HTTP protocol), we have to indicate the path which contains the requested page.For example if you want to download the Wikipedia page on the Arduino to be reached at the following address it.wikipedia.org/wiki/Arduino_(hardware), the path will be /wiki/Arduino_ (hardware) while the server is it.wikipedia.org.

numdata=inet.httpGET(“it.wikipedia.org “, 80, “/wiki/Arduino_(hardware) “, msg, 50);

Obviously if we wish to save a greater number of characters of the answer, it is sufficient to initialize a string of larger dimensions, taking care not to saturate the RAM is made available by Arduino, otherwise we risk getting abnormal behavior, such as stalls or restarts.

#include "SIM900.h"
#include <SoftwareSerial.h>
#include "inetGSM.h"

InetGSM inet;              

char msg[50];
int numdata;
char inSerial[50];
int i=0;
boolean started=false;

void setup()
{
  Serial.begin(9600);
  Serial.println("GSM Shield testing.");
  if (gsm.begin(2400)){
    Serial.println("\nstatus=READY");
    started=true; 
  }
  else Serial.println("\nstatus=IDLE");

  if(started){
    if (inet.attachGPRS("internet.wind","", ""))
      Serial.println("status=ATTACHED");
    else Serial.println("status=ERROR");
    delay(1000);

    gsm.SimpleWriteln("AT+CIFSR");
    delay(5000);
    gsm.WhileSimpleRead();
    numdata=inet.httpGET("www.google.com", 80, "/", msg, 50);
    Serial.println("\nNumero di byte ricevuti:");
    Serial.println(numdata); 
    Serial.println("\nData recived:");
    Serial.println(msg);
  }
};
void loop()
{
};

 

The shield has various connectors to accept more GSM/GPRS modules manufactured by SIMCOM and mounted on breakout board. In addition to the popular SIM900, our new shield for Arduino supports the recent SIM908, which is an evolution and aims to capture the market of GSM/GPRS quad-band providing a variety of additional features that make it unique, especially in the field of low-cost products. The SIM908 implements a GPS with 42 channels, characterized by an excellent accuracy and by a very reduced time required to perform the first fix (1 second in mode “hot start” and 30 seconds with the mode “cold start”).
This module can be used powered by a lithium battery, and can charge it, greatly simplifying this process that would require dedicated hardware.

The SIM908 has two serial, used one for the GSM and the other for the GPS. More exactly, the first serial interface is provided with a UART which belongs to the lines TXD, RXD, DTR, which go outside through the contacts, respectively, 12, 14, 10 of connector; for the GPS, instead, the serial is GPSTXD (contact 4) and GPSRXD (pin 5). The first serial port is actually intended for total control of SIM908, then it can also configure the GPS receiver and ask him to provide data on the location, the number of satellites hooked, etc. From the second serial port (GPSTXD / GPSRXD) instead, go out continuously strings in standard NMEA GPS system.

 

 

THE GSM SHIELD LIBRARY

Providing also use the SIM908, the library for the management of this module has been modified to provide a quick access to all the new features made available, the new library is derived from that used for the SIM900 module, and is available on the Internet at http://code.google.com/p/gsm-shield-arduino/ .

Note that you can use the new library for managing mobile SIM900, provided you do not call functions dedicated to SIM908. While it is completely compatible using the sketch for the version without GPS with this new one.

Let’s consider some new features introduced: first of all has been added the function ForceON(); used to check the status of the module and to force the power on. The SIM908 supports the charge of lithium batteries, the module can be started to perform the charger without the management of the GSM network. If we want to avoid this mode and make sure it’s really turned on then you need to call the function mentioned above.

gsm.forceON();

Intended for the use of GPS (and battery), we made a class which you can instantiate an object with GPSGSM gps, after including its # include files “gps.h“, in order to invoke their functions by prefixing “GSM.” to the desired function.

This subdivision into different files is designed to minimize RAM usage: in fact, for example, all the variables used by the class on the GPS will not be allocated in memory will not be included if the relevant files using #include “gps.h”.This allows you to choose which variables to use.

As already mentioned, also for the management of the battery there ara functions which enable the measurement of the voltage and battery temperature; for practical reasons, occupying little memory, these have been included in the class of GPS. For use them, after including the file #include “gps.h” you must instantiate the object related with GPSGSM gps. In the next sections will show the control functions of the GPS and battery.

 

HOW TO USE THE SIM908 GPS 

Before using GPS, you need to make a small set-up: first let’s make a bridge on jumper J1 on the SIM908 Breakout (cod. FT971).

The bridge on J1 enables power to the GPS antenna.

This serves to bring power to the active GPS antenna. Next, load the sketch example (in the examples directory) called GSM_GPRS_GPS_Library_AT (or even GSM_GPRSLibrary_AT) and once launched and completed initialization send the following commands:

 

AT

AT+CGPSPWR=1

AT+CGSPRST=0

 

We wait a minute, at which point the GPS should be working, to verify

continue sending the command:

 

AT+CGPSINF=0

 

If you can see the coordinates, it means that everything is working and we can proceed with the standard use by the implemented functions.

 

char attachGPS() Follow the steps to activate the GPS: turn on the power and set the mode to “hot start”. gps.attachGPS()
char deattachGPS() power off, disabling the power supply to save energy. gps.deattachGPS()
char getStat() Check the GPS status, the possible outputs are:0: GPS not started.1: Fix not performed (can be caused by a signal of poor quality).2: Fix 2D run.3: Fix 3D executed. char stat;
stat=gps.getStat();
if(stat==3)
Serial.println(“FIXED”);
char getPar(char* str_long, char* str_lat, char* str_alt, char* str_time, char* speed); Save in variables, respectively, longitude, latitude, altitude, time and speed. char lon[10];
char lat[10];
char alt[10];
char time[15];
char vel[10];
gps.getPar(lon,lat,alt,time,vel);

 

Now we proceed with a simple example that allows us to understand how to get the coordinates from the GPS module SIM908 mounted on the shield, the firmware is described here:

 

#include "SIM900.h"

#include <SoftwareSerial.h>

#include "gps.h"              

GPSGSM gps;                   

char lon[10];   
char lat[10];   
char alt[10];   
char time[15];  
char vel[10];   
char stat;      
boolean started=false;

void setup()
{
  //Serial connection.
 Serial.begin(9600);

  Serial.println("GSM GPRS GPS Shield");

  if (gsm.begin(2400)){

    Serial.println("\nstatus=READY");
    gsm.forceON();              
    started=true; 
  }
  else Serial.println("\nstatus=IDLE");

  if(started){
    if (gps.attachGPS())
      Serial.println("status=GPSON");
    else Serial.println("status=ERROR");

    delay(20000);              

    stat=gps.getStat();        

              if(stat==1)
                            Serial.println("NOT FIXED");
              else if(stat==0)
                            Serial.println("GPS OFF");
              else if(stat==2)
                            Serial.println("2D FIXED");
              else if(stat==3)
                            Serial.println("3D FIXED");
              delay(5000);

              gps.getPar(lon,lat,alt,time,vel);
              Serial.println(lon);
              Serial.println(lat);
              Serial.println(alt);
              Serial.println(time);
              Serial.println(vel);
  }
};

void loop()

{

};

 

THE BATTERY

In order to use the lithium battery as the power source for our FT971 module that houses the SIM908 (note: the SIM900 is not able to manage the barrery charge) is sufficient to close the bridge on this shield called with CHRG and set on VEXT the second bridge near the battery connector.

Through the two library functions is possible to obtain the percentage of remaining charge, the battery voltage and the voltage read by the temperature sensor. In the case of applications poorly ventilated, with prolonged periods of work and in climatic conditions not exactly optimal, it is advisable to monitor this value to make sure that the battery works within the limits for a correct operation. The temperature can be calculated according to the relationship voltage/temperature sensor.

It is also possible to set the module so that automatically determine if the battery is working outside the permissible range, with consequent shutdown of the same.

To activate this mode, you need to send the command:

 

AT+CMTE=1

 

To disable it you have to send the command:

 

AT+CMTE=0

 

While to know which mode is configured must issue the command:

 

AT+CMTE?

 

To know the exact syntax of the functions and their return refer to Table:

 

char getBattInf(char* str_perc, char* str_vol); Save the remaining battery in percentage terms, and battery voltage. char str_perc[5];
char str_vol[6];
gps.getBattInf(str_perc,str_vol);
Serial.print(“BATTERY: ”);
Serial.print(str_perc);
Serial.println(“%”);
char getBattTVol(char* str_vol); Saves the voltage value of the temperature sensor. char str_Tvol[6];
gps.getBattTVol(str_Tvol);
Serial.println(str_Tvol);

Also in this case we see how to implement these functions in a sketch, referring to this sketch, which contains the corresponding code.

 

 

#include "SIM900.h"

#include <SoftwareSerial.h>

#include "inetGSM.h"

#include "gps.h"           

GPSGSM gps;                

char perc[5];              
char volt[6];              
char tvolt[6];             

long prevmillis=millis();              
int interval=10000;               

void setup()
{

  Serial.begin(9600);
  Serial.println("GSM GPRS GPS Shield.");
  if (gsm.begin(4800)){
    Serial.println("\nstatus=READY");
    gsm.forceON();  }

  else Serial.println("\nstatus=IDLE");

};

void loop()

{

  if(millis()-prevmillis>interval){     

    gps.getBattInf(perc,volt);          
    gps.getBattTVol(tvolt);             

    Serial.print("Battery charge: ");
    Serial.print(perc);
    Serial.println("%");

    Serial.print("Battery voltage: ");
    Serial.print(volt);
    Serial.println(" mV");

    Serial.print("Temperature sensor voltage: ");
    Serial.print(tvolt);
    Serial.println(" mV");  

    Serial.println("");

    prevmillis=millis();
  }
}

 

DEBUG MODE GSM & GPS SHIELD

During the use of the shield, sometimes you fail to get the desired results without understanding why, for help, libraries can be configured to provide output some debug messages during the execution of functions called. Inside the file GSM.h there is the following line:

 

//#define DEBUG_ON

 

Uncomment it, you are going to enable this mode, commenting, no diagnostic message will be shown on the serial output.

 

HOW TO USE THE GSM & GPS SHIELD WITH ARDUINO MEGA

For problems with the RAM, or simply for projects that require a larger number of input/output, we can use with the GSM/GPRS & GPS shield the Arduino Mega.  Thanks to four serial port, we can use one of these instead of the serial software to communicate with the shield.

With the latest release, the library can be used completely with Arduino Mega. You must open the file GSM.h and select the tab used appropriately commenting lines of code.

Using the shield with Arduino Mega we comment as follows:

 

//#define UNO

#define MEGA

If we want to use Arduino UNO:

#define UNO

//#define MEGA

 

Similarly, also the file HWSerial.h, must be configured. As before, we see the first example for Arduino Mega:

 

#define MEGA

 

Using the file HWSerial.h is not necessary to define the possible use with Arduino Uno, as implemented in the class it is only used by the hardware serial.

The library uses the serial Serial0 (TX 1 RX 0) for external communication and the serial Serial1 (RX 18 TX 19) to communicate with SIM900 and SIM908. Nothing prevents you replace every occurrence of Serial1 with Serial2 or one that you prefer.

Please note that to use the serial hardware you need to create the connection between the shield and Arduino Mega using a bridge: the TX pin of the shield must be connected to TX1 18 and the RX pin with the RX1 19.

 

 

THE STORE

 

 

 

 

-->-->-->-->-->-->
-->-->