PubNub's Ian Jennings demonstrates how to connect your Arduino to a mobile cellular network with a GSM/GPRS shield.
There's a ton of tutorials out there on hooking your Arduino up to the LAN, whether it be Wi-Fi, an Ethernet, or other. But what about beyond the LAN? What if you want to connect your Arduino to the Internet in the wild? In this tutorial from PubNub’s Developer Evangelist Ian Jennings, we'll show you how to connect your Arduino to a mobile cellular network with a GSM/GPRS shield. This enables you to stream data bidirectionally or trigger device actions anywhere with a cellular network. And, that's powerful for any mobile IoT implementation (think connected car or drones) or apps without a Wi-Fi signal (think irrigation or weather sensor networks). Like like the many other DIY Arduino projects out there, it's easy, affordable, and powerful. So let's get the tutorial started!
The first thing you'll need to do is unlock the SIM card and make sure it has a data plan associated with it (hence why we included the smartphone on the list above). Put the SIM card into your phone and read the instructions on the package.
In the case of an AT&T SIM card, you may have to dial a series of numbers to activate the card, then configure the plan online, but this may vary depending on the carrier. Note: Make sure your mobile plan supports data transfer and not just calls and texts.Then, connect to a website on your mobile phone. If it works, you have data and the SIM card will work on your Arduino.
Plug in your now-activated SIM card to your Arduino GPRS Shield. For how to do this, Seeed Studio has a great tutorial. Follow the tutorial, but stop and come back to this tutorial before uploading code in "Test Setup."
There are a fair amount of libraries needed to get setup on Arduino, but at the end, it'll make it all a lot easier. The specific libraries for the Seeed Studio GPRS Shield v2 can be found here. In the docs, you'll see the three libraries you'll need to connect to a mobile network. Import all three libraries into the Arduino setup.
Now that our shield and Arduino environment are ready, let's move onto the fun part of this tutorial: playing with the cell networks. We need a way to talk to the SIM900 chip on the Arduino. Instead of using a hardware serial and talking directly to it, we're going to use Arduino's software serial. Open up the SIM_900_Serial_Debug example from your Arduino examples folder.
SIM_900_Serial_Debug
This example is pretty simple. All we're doing it proxying the serial data from Arduino's serial port into SIM900's. This enables us to use the included Arduino serial debug tool to interact with our SIM900.
void loop(){ if(gprs.available()){ Serial.write(gprs.read()); } if(Serial.available()){ gprs.write(Serial.read()); } }
To test everything out, we're going to attempt to call ourselves with the Arduino GSM shield. First, load the software serial example onto the Arduino and then open up the serial debugger. Be sure to power the SIM card on the Arduino GPRS shield using the button on the side. Power up the SIM900 by pressing the power button for around 2 seconds. The red LED will turn on. The green one beside it will begin blinking. If the shield joins the network successfully, the green LED will blink every 3 seconds. Wonderful!Make sure you put your old SMS card back into your phone after testing the Arduino SIM. Now, type the following into your Arduino serial window.
AT
Serial output should show something like:
RDY +CFUN: 1 +CPIN: READY +PACSP: 0 Call Ready
If you don't see the messages in the serial monitor, click the "send new" option that will add carriage return at the end of AT command, and then send AT command “AT+IPR=19200″ to set the baud rate of the SIM900. Now try calling yourself. Enter the following command, replacing 1***8675309with your own number.
1***8675309
ATD1***8675309;
If it succeeds, a message ATH OK will show up as the picture below. Otherwise, No CARRIERwill show up instead. The reason might be nonexistent phone number or incorrect command format.
ATH OK
No CARRIER
Now that we've configured our Arduino to work over GSM, let's get it connected to the mobile cellular network. Make sure that the baud rate of SIM900 is 9600! You can use the AT Command(AT+IPR=9600) to set it through SerialDebug. Load up the the GPRS_TCPConnection example from GPRS_Shield_Suli. This example makes a simple request tombed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\r\n\r\nHowever, it probably won’t run when you load it on your Arduino. This is because it’s not configured to work with your specific cellular network. In my case I’m using AT&T, so I needed to change the following lines to configure my GPRS connection:
mbed.org/media/uploads/mbed_official/hello.txt HTTP/1.0\r\n\r\n
GPRS gprs(PIN_TX, PIN_RX, BAUDRATE,"cmnet");
This line isn’t sufficient in most cases. We’ll also need to supply an APN, username, and password. These parameters are omitted from the example but you can simply supply them on your own. You can find the relevant code here.
GPRS(int tx, int rx, uint32_t baudRate = 9600, const char* apn = NULL, const char* userName = NULL, const char *passWord = NULL);
To connect to AT&T, use the following config:
GPRS gprs(PIN_TX, PIN_RX, BAUDRATE, "wap.cingular", "WAP@CINGULARGPRS.COM", "CINGULAR1");
Now run the code. You should be able to obtain an IP and issue the request. However, the app will probably crash (SIM turns off) when the request has been issued. This might be confusing, but there’s an easy fix.
The Seeed Studio and a variety of other shields advertise to be “plug and play” with Arduino. However, this isn't always the case. This shield in particular doesn’t have enough power from the single 5v USB supply to successfully complete TCP requests. This is easy enough to fix though, all we need to do is give it more power! Online forums suggest adding 5 C-cell batteries to power the GSM chip, which is what we did below:
The batteries should be wired in series, with the positive end wired into the VIN input and negative wired into the GND. After you’ve added batteries, try the example again. It should connect successfully. Great! Now we’re ready to signal with PubNub.
We're going to use the PubNub Data Stream Network as our backend messaging layer for signaling our Arduino. This enables you to send and receive data bidirectionally between your Arduinos and signal to trigger device actions. Load the following example onto your Arduino, changing the GPRS gprs() configuration as mentioned previously.
GPRS gprs()
#include #include #include #include
void publishData(String data) {
while (false == gprs.join()) { Serial.println("gprs join network error"); delay(2000); }
// Length (with one extra character for the null terminator) int str_len = str.length() + 1;
// Copy it over str.toCharArray(http_cmd, str_len);
if (false == gprs.connect(TCP, "pubsub.pubnub.com", 80)) { Serial.println("connect error"); } else { Serial.println("publish success"); Serial.println(data); }
gprs.close();
int counter = 0;
Serial.println("starting");
while(true){ publishData(String(counter)); counter++; delay(1000); }
} }
This example connects to PubNub and publishes a message every second. It works just like the previous example, but instead of retrieving data, this example streams information to the PubNub network where it’s accessible from anywhere.
You can see how the message is assembled by looking at the publishData() function. See how the url is created here:
publishData()
String str = "GET /publish/demo/demo/0/pubnub_gprs/0/\"" + data + "\" HTTP/1.0\r\n\r\n";
It may be confusing at first, but let’s break it down. The url is formatted according to the PubNub REST Push API.
http://pubsub.pubnub.com /publish /pub-key /sub-key /signature /channel /callback /message
The domain pubsub.pubnub.com is defined later in the function. The publish key refers to is the pubnub command (you can also subscribe). The pub-key and sub-key come from your own PubNub account, but you can use thedemo keys for now. Don’t worry about signature. The channel is really important. This is like an IRC channel for your PubNub devices to talk to each other.
pubsub.pubnub.com
publish
pub-key
sub-key
demo
channel
Since we don’t have any other device listening for messages from the Arduino, let’s use the PubNub console to observe our channel activity. If you’re using the default code above, you can use this link to view channel activity for your GPRS chip. If your demo is running you should see a count like 1, 2, 3, 4 appear in the “message” pane.
We’re able to view the data coming out of the Arduino because we plugged the same publish and subscribe key into the PubNub console as we did into the Arduino. Since we’re using the demo keys the channel is shared publicly, but if you create your own account your data will be privatized.
This is just one of our many Arduino-PubNub implementations. We’ve also connected Arduino Yún to the Internet, as well as showing you how to connect Arduino Uno and Seeed Studio Ethernet Shield v2. For all our Arduino related posts, here’s the full feed.
Ian Jennings is a developer evangelist at PubNub, a secure global data stream network for IoT, mobile, and web applications. He cofounded Hacker League, a site devoted to simplifying the organization of intensely collaborative tech events known as "hackathons." Jennings recently pretty much guaranteed that he'll always be able to keep himself stocked up on techno-gadgets with the sale of Hacker League to Intel's Mashery subdivision for the price of more than a few PCs. But he's not done. In fact, his latest invention, Mote.io, is a remote that connects your web browser with various music platforms like Pandora, Youtube, and Rdio, and has gotten raves on tech sites like GigaOM; he’s also in the midst of developing the Reddit app for the uber-hyped tech accessory Google Glass.