Learning   Examples | Foundations | Hacking | Links

Examples > GSM library

GSM Twitter Client

This example no longer works as the Twitter authentication mode has changed, and is no longer compatible with the Arduino library.

The Arduino Yún supports OAuth through Temboo. Learn more in the Temboo documentation.

This sketch connects to Twitter using an Ethernet shield. It parses the XML returned, and looks for <text>this is a tweet</text>.

Make sure your SIM is data enabled and you have the necessary information to connect to the network. You'll need the Access Point Name (APN), login, and password of the carrier. To obtain this information, contact your network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.

Hardware Required

  • Arduino board
  • Arduino + Telefonica GSM/GPRS Shield
  • SIM card with a data connection

Circuit

image of the Arduino GSM Shield on top of an Arduino Uno

First, import the GSM library

#include <GSM.h>

SIM cards may have a PIN number that enables their functionality. Define the PIN for your SIM. If your SIM has no PIN, you can leave it blank :

#define PINNUMBER ""

Define a number of constants that contain information about the GPRS network you're going to connect to. You'll need the Access Point Name (APN), login, and password. To obtain this information, contact your network provider for the most up to date information. This page has some information about various carrier settings, but it may not be current.

#define GPRS_APN       "GPRS_APN"
#define GPRS_LOGIN     "login"
#define GPRS_PASSWORD  "password"

Initialize instances of the classes you're going to use. You're going to need the GSM, GPRS, and GSMClient classes.

GPRS gprs;
GSM gsmAccess;
GSMClient client;

Create a variable for determining the time between requests. 30 seconds should suffice.

const unsigned long requestInterval = 30*1000;

Make an array to hold the Twitter API URL

char server[] = "api.twitter.com";

Declare variables for determining if you have made a request recently, and the time since your last request

boolean requested;
unsigned long lastAttemptTime = 0;

Create some Strings to hold text from the server and the tweet itself. Also create a flag to indicate if the program is currently reading a tweet or not.

String currentLine = "";
String tweet = "";
boolean readingTweet = false;

In setup, reserve space for the strings :

currentLine.reserve(256);
  tweet.reserve(150);

Open a serial connection to the computer. After opening the connection, send a message indicating the sketch has started.

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

Create a local variable to track the connection status. You'll use this to keep the sketch from starting until the SIM is connected to the network :

boolean notConnected = true;

Connect to the network by calling gsmAccess.begin(). It takes the SIM card's PIN as an argument. You'll also connect to the GPRS network using gprs.attachGPRS(). This requires the APN, login, and password you declared earlier. By placing this inside a while() loop, you can continually check the status of the connection and wait for them to both become true before proceeding.

When the modem does connect and has attached itself to the GPRS network, gsmAccess() will return GSM_READY. Use this as a flag to set the notConnected variable to true or false. Once connected, the remainder of setup will run.

while(notConnected)
  {
    if(gsmAccess.begin(PINNUMBER)==GSM_READY)
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

Print out the status, and call a custom function named @connectToServer() before closing the setup@@.

Serial.println("Connected to GPRS network");

  Serial.println("connecting...");
  connectToServer();
}

The connectToServer() function will connect to the API server and request the timeline of the arduinoteam twitter account. Use client.connect() to connect to the api server.

void connectToServer()
{
  Serial.println("connecting to server...");
  if (client.connect(server, 80))
  {

Once connected, make the HTTP request to twitter:

Serial.println("making HTTP request...");
    // make HTTP GET request to twitter:
    client.println("GET /1/statuses/user_timeline.xml?screen_name=arduinoteam HTTP/1.1");
    client.println("HOST: api.twitter.com");
    client.println();
  }

Update the lastAttemptTime variable to the current time, and close the function.

lastAttemptTime = millis();
}

In loop, check if the Arduino is connected to the server and there are bytes to be read. If so, start to add them to the array currentLine.

void loop()
{
  if (client.connected())
  {
    if (client.available())
    {
      // read incoming bytes:
      char inChar = client.read();

      // add incoming byte to end of line:
      currentLine += inChar;

If the character is a newline, clear the array.

if (inChar == '\n')
      {
        currentLine = "";
      }

If the current line ends with <text>, it will be followed by the tweet. Using endsWith(), you can identify when the tweet begins :

if (currentLine.endsWith("<text>"))
      {
        readingTweet = true;
        tweet = "";
      }

If a tweet is currently being read, add the characters to the tweet String :

if (readingTweet)
      {
        if (inChar != '<')
        {
          tweet += inChar;
        }

A '<' character indicates the end of a tweet. Change the readingTweet flag to false, send the tweet to the serial monitor, and stop the client.

else
        {
          // if you got a "<" character,
          // you've reached the end of the tweet:
          readingTweet = false;
          Serial.println(tweet);  

          // close the connection to the server:
          client.stop();
        }
      }
    }  
  }

Finally, check to see how long it has been since the last time a connection was made. If it has been longer than the request interval, call connectToServer() again and read the most recent message. Close up the loop.

else if (millis() - lastAttemptTime > requestInterval)
  {
    connectToServer();
  }
}

Once your code is uploaded, open the serial monitor. You should see the most recent tweet from the arduinoteam twitter account in the serial monitor after a connection has been established.

/*
  GSM Twitter Client with Strings

 This sketch connects to Twitter using using an Arduino GSM shield.
 It parses the XML returned, and looks for <text>this is a tweet</text>

 This example uses the String library, which is part of the Arduino core from
 version 0019.  

 Circuit:
 * GSM shield attached to pins 10, 11, 12, 13

 created 8 Mar 2012
 by Tom Igoe

 This code is in the public domain.

 */


// libraries
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// APN data
#define GPRS_APN       "APN" // replace your GPRS APN
#define GPRS_LOGIN     "LOGIN" // replace with your GPRS login
#define GPRS_PASSWORD  "PASSWORD" // replace with your GPRS password

// initialize the library instance
GSMClient client;
GPRS gprs;
GSM GSMAccess; // include a 'true' parameter for debug enabled

const unsigned long requestInterval = 30*1000;    // delay between requests; 30 seconds

// API Twitter URL
char server[] = "api.twitter.com";

boolean requested;                     // whether you've made a request since connecting
unsigned long lastAttemptTime = 0;     // last time you connected to the server, in milliseconds

String currentLine = "";               // string to hold the text from server
String tweet = "";                     // string to hold the tweet
boolean readingTweet = false;          // if you're currently reading the tweet

void setup()
{
  // reserve space for the strings:
  currentLine.reserve(256);
  tweet.reserve(150);

  // initialize serial communications
  Serial.begin(9600);

  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // If your SIM has PIN, pass it as a parameter of begin() in quotes
  while(notConnected)
  {
    if((GSMAccess.begin(PINNUMBER)==GSM_READY) &
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY))
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("Connected to GPRS network");

  Serial.println("connecting...");
  connectToServer();
}



void loop()
{
  char c;
  if (client.connected())
  {
    if (client.available())
    {
      // read incoming bytes:
      char inChar = client.read();

      // add incoming byte to end of line:
      currentLine += inChar;

      // if you get a newline, clear the line:
      if (inChar == '\n')
      {
        currentLine = "";
      }

      // if the current line ends with <text>, it will
      // be followed by the tweet:
      if (currentLine.endsWith("<text>"))
      {
        // tweet is beginning. Clear the tweet string:
        readingTweet = true;
        tweet = "";
      }

      // if you're currently reading the bytes of a tweet,
      // add them to the tweet String:
      if (readingTweet)
      {
        if (inChar != '<')
        {
          tweet += inChar;
        }
        else
        {
          // if you got a "<" character,
          // you've reached the end of the tweet:
          readingTweet = false;
          Serial.println(tweet);  

          // close the connection to the server:
          client.stop();
        }
      }
    }  
  }
  else if (millis() - lastAttemptTime > requestInterval)
  {
    // if you're not connected, and two minutes have passed since
    // your last connection, then attempt to connect again:
    connectToServer();
  }
}

/*
  Connect to API Twitter server and do a request for timeline
*/

void connectToServer()
{
  // attempt to connect, and wait a millisecond:
  Serial.println("connecting to server...");
  if (client.connect(server, 80))
  {
    Serial.println("making HTTP request...");
    // make HTTP GET request to twitter:
    client.println("GET /1/statuses/user_timeline.xml?screen_name=arduinoteam HTTP/1.1");
    client.println("HOST: api.twitter.com");
    client.println();
  }
  // note the time of this connect attempt:
  lastAttemptTime = millis();
}

See Also:

Share