How to use the GSM shield with Arduino Leonardo and Arduino Mega

How to use the GSM shield with Arduino Leonardo and Arduino Mega

The GSM shield communicates with an attached Arduino through the Software Serial library. By default, communication between the modem and Arduino happens on digital pins 2 and 3. On the Uno this works without modification, but to use the Leonardo or Mega boards, some slight changes are required.
The GSM_TX pin, pin 2 on the shield, sends information to the Arduino. The Arduino relies on an interrupt to know when to read the information on this pin. The Leonardo and Mega do not have interrupt capabilities on pin 2.
You do not need to change any code to program the shield for use with the Mega or Leonardo, the library will change the Arduino's RX pin automatically depending on the board selected in the "Tools" menu of the IDE.

Arduino Leonardo

The GSM library uses digital pin 8 to communicate with the Leonardo. On the GSM shield, connect a jumper wire between digital pins 2 and 8.
Bend the male header attached to pin 2 on the GSM shield to the side so it does not connect with the Leonardo.

 

Arduino Mega

The GSM library uses digital pin 10 to communicate with the Leonardo. On the GSM shield, connect a jumper wire between digital pins 2 and 10.
Bend the male header attached to pin 2 on the GSM shield to the side so it does not connect with the Mega.

 

Using alternate pins with the library

If you prefer to use a different interrupt pin for communication, refer to the Software Serial library reference page to see valid pin choices. You will need to change the __RXPIN__ definition in the GSM3SoftwareSerial.cpp file, located in the GSM library folder.

Testing the modem and network connection

 Testing the modem and network connection

 Testing the modem and network connection

This sketch will check the modem's IMEI number. This number is unique to each modem, and is used to identify valid devices that can connect to a GSM network. Once the number has been read from the modem, the Arduino will print out the network carrier it is connected to, and the signal strength of the network over the serial port.
 
// import the GSM library
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess(true);     // include a 'true' parameter for debug enabled
GSMScanner scannerNetworks;
GSMModem modemTest;

// Save data variables
String IMEI = "";

// serial monitor result messages
String errortext = "ERROR";

void setup()
{
  // initialize serial communications
  Serial.begin(9600);
  Serial.println("GSM networks scanner");
  scannerNetworks.begin();

  // 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)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  // get modem parameters
  // IMEI, modem unique identifier
  Serial.print("Modem IMEI: ");
  IMEI = modemTest.getIMEI();
  IMEI.replace("\n","");
  if(IMEI != NULL)
    Serial.println(IMEI);

  // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");
}

void loop()
{
  // scan for existing networks, displays a list of networks
  Serial.println("Scanning available networks. May take some seconds.");

  Serial.println(scannerNetworks.readNetworks());

    // currently connected carrier
  Serial.print("Current carrier: ");
  Serial.println(scannerNetworks.getCurrentCarrier());

  // returns strength and ber
  // signal strength in 0-31 scale. 31 means power > 51dBm
  // BER is the Bit Error Rate. 0-7 scale. 99=not detectable
  Serial.print("Signal Strength: ");
  Serial.print(scannerNetworks.getSignalStrength());
  Serial.println(" [0-31]");

}

 

Making voice calls With Arduino + GSM Shield

Making voice calls

Through the modem, it is possible to make voice calls. In order to speak to and hear the other party, you will need to add a speaker and microphone. 


On the underside of the shield, there are through-holes labeled M1P and M1N. These are the positive and negative voice input pins for a microphone. The through-holes labeled S1P and S1N are the positive and negative voice output pins, to which you need to connect a speaker.
On page 43 of the modem documentation, there is an example voice and sound circuit that will connect to an earphone:
The following sketch allows you to place a voice call. Using the serial monitor, you can enter the remote phone number and terminate the call. When you see the READY message, type a phone number. Make sure the serial monitor is set to send a just newline when you press return.
 
#include <GSM.h>

// PIN Number
#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSMVoiceCall vcs;

String remoteNumber = "";  // the number you will call
char charbuffer[20];

void setup()
{

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

  Serial.println("Make Voice Call");

  // 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)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }

  Serial.println("GSM initialized.");
  Serial.println("Enter phone number to call.");

}

void loop()
{

  // add any incoming characters to the String:
  while (Serial.available() > 0)
  {
    char inChar = Serial.read();
    // if it's a newline, that means you should make the call:
    if (inChar == '\n')
    {
      // make sure the phone number is not too long:
      if (remoteNumber.length() < 20)
      {
        // show the number you're calling:
        Serial.print("Calling to : ");
        Serial.println(remoteNumber);
        Serial.println();

        // Call the remote number
        remoteNumber.toCharArray(charbuffer, 20);


        // Check if the receiving end has picked up the call
        if(vcs.voiceCall(charbuffer))
        {
          Serial.println("Call Established. Enter line to end");
          // Wait for some input from the line
          while(Serial.read()!='\n' && (vcs.getvoiceCallStatus()==TALKING));        
          // And hang up
          vcs.hangCall();
        }
        Serial.println("Call Finished");
        remoteNumber="";
        Serial.println("Enter phone number to call.");
      }
      else
      {
        Serial.println("That's too long for a phone number. I'm forgetting it");
        remoteNumber = "";
      }
    }
    else
    {
      // add the latest character to the message to send:
      if(inChar!='\r')
        remoteNumber += inChar;
    }
  }
}
 

Connecting to the internet With Arduino & GSM Shield

Connecting to the internet

In addition to the SIM card and a data plan, you will need some additional information from your cellular provider to connect to the internet. Every cellular provider has an Access Point Name (APN) that serves as a bridge between the cellular network and the internet. Sometimes, there is a username and password associated with the connection point. For example, the Bluevia APN is bluevia.movistar.es, but it has no password or login name.
This page lists a number of carrier's information, but it may not be up to date. You may need to get this information from your service provider.
The sketch below will connect to arduino.cc/latest.txt and print out its contents.
NB: Some network operators block incoming IP traffic. You should be able to run client functions, such as the sketch below, with no issues.
 
// include the GSM library
#include <GSM.h>

// PIN number if necessary
#define PINNUMBER ""

// APN information obrained from your network provider
#define GPRS_APN       "GPRS_APN" // replace with your GPRS APN
#define GPRS_LOGIN     "login"    // replace with your GPRS login
#define GPRS_PASSWORD  "password" // replace with your GPRS password

// initialize the library instances
GSMClient client;
GPRS gprs;
GSM gsmAccess;

// This example downloads the URL "http://arduino.cc/latest.txt"

char server[] = "arduino.cc"; // the base URL
char path[] = "/latest.txt"; // the path
int port = 80; // the port, 80 for HTTP

void setup()
{
  // initialize serial communications
  Serial.begin(9600);
  Serial.println("Starting Arduino web client.");
  // connection state
  boolean notConnected = true;

  // Start GSM shield
  // pass the PIN of your SIM as a parameter of gsmAccess.begin()
  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("connecting...");

  // if you get a connection, report back via serial:
  if (client.connect(server, port))
  {
    Serial.println("connected");
    // Make a HTTP request:
    client.print("GET ");
    client.print(path);
    client.println(" HTTP/1.0");
    client.println();
  }
  else
  {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
}

void loop()
{
  // if there are incoming bytes available
  // from the server, read them and print them:
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  // if the server's disconnected, stop the client:
  if (!client.available() && !client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();

    // do nothing forevermore:
    for(;;)
      ;
  }
}

 

Sending a SMS message Through Arduino UNO & GSM Shield

Sending a SMS message

Once you have connected to your network with the sketch above, you can test some of the other functionality of the board. This sketch will connect to a GSM network and send a SMS message to a phone number of your choosing.

#include <GSM.h>

#define PINNUMBER ""

// initialize the library instance
GSM gsmAccess; // include a 'true' parameter for debug enabled
GSM_SMS sms;

// char array of the telephone number to send SMS
// change the number 1-212-555-1212 to a number
// you have access to
char remoteNumber[20]= "12125551212";

// char array of the message
char txtMsg[200]="Test";

void setup()
{
  // initialize serial communications
  Serial.begin(9600);

  Serial.println("SMS Messages Sender");

  // 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)
      notConnected = false;
    else
    {
      Serial.println("Not connected");
      delay(1000);
    }
  }
  Serial.println("GSM initialized");
  sendSMS();
}

void loop()
{
// nothing to see here
}

void sendSMS(){

  Serial.print("Message to mobile number: ");
  Serial.println(remoteNumber);

  // sms text
  Serial.println("SENDING");
  Serial.println();
  Serial.println("Message:");
  Serial.println(txtMsg);

  // send the message
  sms.beginSMS(remoteNumber);
  sms.print(txtMsg);
  sms.endSMS();
  Serial.println("\nCOMPLETE!\n");
}

 

Connecting the Shield With Arduino UNO

If you are using an Arduino Uno, follow the instructions below. If you are using an Arduino Mega, Mega ADK, or Leonardo, you must follow other instructions( see our next post ). The GSM shield is not currently supported on the Due.
To use the shield, you'll need to insert a SIM card into the holder. Slide the metal bracket away from the edge of the shield and lift the cradle up. 


Insert the SIM in the plastic holder so the metal contacts are facing the shield, with the notch of the card at the top of the bracket. 


Slide the SIM all the way into the bracket 


Push the SIM to the board and slide the metal bracket towards the edge of the shield to lock it in place. 


Once the SIM is inserted, mount it on top of an Arduino board. 


To upload sketches to the board, connect it to your computer with a USB cable and upload your sketch with the Arduino IDE. Once the sketch has been uploaded, you can disconnect the board from your computer and power it with an external power supply. 


Digital pins 2, 3 and 7 are reserved for communication between the Arduino and modem and cannot be used by your sketches. Communication between the moden and Arduino is handled by the Software Serial library on pins 2 and 3. Pin 7 is used for the modem reset.
When the yellow status LED turns on, it means the modem is powered, and you can try connecting to the network.
Developer versions of the GSM shield required you to press press the Power button on the shield for a few moments to turn the modem on. If you have an early version of the shield, and it does not turn on automatically, you can solder a jumper to the CTRL/D7 pad on the reverse side of the board, and it will turn on when an attached Arduino receives power. 


The shield should work in any area with GSM coverage. Before buying the shield please verify that there is this kind of coverage where you plan to use it.

GSM Library

The GSM library handles communication between Arduino and the GSM shield. The majority of functions are for managing data, voice, and SMS communication. There are also a number of utilities for managing information about the modem and the SIM card's PIN.

Arduino GSM Shield

Arduino GSM Shield Front
Arduino GSM Shield Front
Arduino GSM Shield Rear
Arduino GSM ShieldRear
Making a Call From Arduino GSM Shield

The Arduino GSM shield allows an Arduino board to connect to the internet, send and receive SMS, and make voice calls using the GSM library.
The shield will work with the Arduino Uno out of the box. The shield will work with the Mega, Mega ADK, and Leonardo boards with a minor modification. The Due is not supported at this time.
The GSM library is included with Arduino IDE 1.0.4 and later.

**Don't Click on Play If you dont want to spend your internet bandwidth for viewing this video just read on...

Firstly Lets See The Trailer of Arduino's GSM Shield:
Lets See the Introduction Of Arduino's GSM Shield Video (Part 1)!!


Now Lets See the Introduction Of Arduino's GSM Shield Video (Part 2)!!

So What is GSM

GSM is an international standard for mobile telephones. It is an acronym that stands for Global System for Mobile Communications. It is also sometimes referred to as 2G, as it is a second-generation cellular netwTo use GPRS for internet access, and for the Arduino to request or serve webpages, you need to obtain the Access Point Name (APN) and a username/password from the network operator. See the information in Connecting to the Internet for more information about using the data capabilities of the shield.
Among other things, GSM supports outgoing and incoming voice calls, Simple Message System (SMS or text messaging), and data communication (via GPRS). 


What is GPRS

GPRS is a packet switching technology that stands for General Packet Radio Service. It can provide idealized data rates between 56-114 kbit per second.
A number of technologies such as SMS rely on GPRS to function. With the GSM shield, it is also possible to leverage the data communication to access the internet. Similar to the Ethernet and WiFi libraries, the GSM library allows the Arduino to act as a client or server, using http calls to send and receive web pages.

Network operator requirements

To access a network, you must have a subscription with a mobile phone operator (either prepaid or contract), a GSM compliant device like the GSM shield or mobile phone, and a Subscriber Identity Module (SIM) card. The network operator provides the SIM card, which contains information like the mobile number, and can store limited amounts of contacts and SMS messages.
To use GPRS for internet access, and for the Arduino to request or serve webpages, you need to obtain the Access Point Name (APN) and a username/password from the network operator. See the information in Connecting to the Internet for more information about using the data capabilities of the shield.


SIM cards

In addition to the GSM shield and an Arduino, you need a SIM card. The SIM represents a contract with a communications provider. The communications provider selling you the SIM has to either provide GSM coverage where you are, or have a roaming agreement with a company providing GSM coverage in your location.
It's common for SIM cards to have a four-digit PIN number associated with them for security purposes. Keep note of this number, as it's necessary for connecting to a network. If you lose the PIN associated with your SIM card, you may need to contact your network operator to retrieve it. Some SIM cards become locked if an incorrect PIN is entered too many times. If you're unsure of what the PIN is, look at the documentation that came with your SIM.
Using a PUK (PIN Unlock Code), it is possible to reset a lost PIN with the GSM shield and an Arduino. The PUK number will come with your SIM card documentation.
Look at the PIN Management example in the "tools" folder, bundled with the GSM library for an example of how to manage your PIN number with the PUK.
There are a few different sizes of SIM cards; the GSM shield accepts cards in the mini-SIM format (25mm long and 15mm wide).


Download: PDF of GSM shield schematic, Reference design
The GSM library is included with Arduino IDE 1.0.4 and later.

Overview

The Arduino GSM Shield connects your Arduino to the internet using the GPRS wireless network. Just plug this module onto your Arduino board, plug in a SIM card from an operator offering GPRS coverage and follow a few simple instructions to start controlling your world through the internet. You can also make/receive voice calls (you will need an external speaker and microphone circuit) and send/receive SMS messages.
As always with Arduino, every element of the platform – hardware, software and documentation – is freely available and open-source. This means you can learn exactly how it's made and use its design as the starting point for your own circuits. Hundreds of thousands of Arduino boards are already fueling people’s creativity all over the world, everyday. Join us now, Arduino is you!
  • Requires and Arduino board (not included)
  • Operating voltage 5V (supplied from the Arduino Board)
  • Connection with Arduino Uno on pins 2, 3 (Software Serial) and 7 (reset). See article for working with a Mega, Mega ADK, or Leonardo.

Description

The Arduino GSM Shield allows an Arduino board to connect to the internet, make/receive voice calls and send/receive SMS messages. The shield uses a radio modem M10 by Quectel (datasheet). It is possible to communicate with the board using AT commands. The GSM library has a large number of methods for communication with the shield.
The shield uses digital pins 2 and 3 for software serial communication with the M10. Pin 2 is connected to the M10’s TX pin and pin 3 to its RX pin.  The modem's PWRKEY pin is connected to Arduino pin 7.
The M10 is a Quad-band GSM/GPRS modem that works at frequencies GSM850MHz, GSM900MHz, DCS1800MHz and PCS1900MHz. It supports TCP/UDP and HTTP protocols through a GPRS connection. GPRS data downlink and uplink transfer speed maximum is 85.6 kbps.
To interface with the cellular network, the board requires a SIM card provided by a network operator. 
The most recent revision of the board uses the 1.0 pinout on rev 3 of the Arduino Uno board.

Notes on the Telefonica/Bluevia SIM included with the shield

The GSM shield comes bundled with a SIM from Telefonica/Bluevia that will work well for developing machine to machine (M2M) applications. It is not necessary to use this specific card with the shield. You may use any SIM that works on a network in your area.
The Bluevia SIM card includes a roaming plan. It can be used on any supported GSM network. There is coverage throughout the Americas and Europe for this SIM, check the Bluevia service availability page for specific countries that have supported networks.
Activation of the SIM is handled by Bluevia. Detailed instructions on how to register and activate your SIM online and add credit are included on a small pamphlet that comes with your shield. The SIM must be inserted into a powered GSM shield that is mounted on an Arduino for activation.
These SIM card come without a PIN, but it is possible to set one using the GSM library's GSMPIN class.
You cannot use the included SIM to place or receive voice calls.
You can only place and receive SMS with other SIMs on the Bluevia network.
It's not possible to create a server that accepts incoming requests from the public internet. However, the Bluevia SIM will accept incoming requests from other SIM cards on the Bluevia network.
For using the voice, and other functions of the shield, you'll need to find a different network provider and SIM. Operators will have different policies for their SIM cards, check with them directly to determine what types of connections are supported.

Power requirements

It is recommended that the board be powered with an external power supply that can provide between 700mA and 1000mA. Powering an Arduino and the GSM shield from a USB connection is not recommended, as USB cannot provide the required current for when the modem is in heavy use.
The modem can pull up to 2A of current at peak usage, which can occur during data transmission. This current is provided through the large orange capacitor on the board's surface.

On board indicators

The shield contains a number of status LEDs:
  • On: shows the Shield gets power.
  • Status: turns on to when the modem is powered and data is being transferred to/from the GSM/GPRS network.
  • Net: blinks when the modem is communicating with the radio network.

On board interfaces

The shield supports AIN1 and AOUT1 as audio interfaces; an analog input channel and an analog output channel. The input, exposed on pins MIC1P/MIC1N, can be used for both microphone and line inputs. An electret microphone can be used for this interface. The output, exposed as lines SPK1P/SPK1N, can be used with either a receiver or speaker. Through the modem, it is possible to make voice calls. In order to speak to and hear the other party, you will need to add a speaker and microphone.
On page 43 of the modem documentation, there is an example voice and sound circuit that will connect to an earphone:
There are two small buttons on the shield. The button labeled "Reset" is tied to the Arduino reset pin. When pressed, it will restart the sketch. The button labeled "Power" is connected to the modem and will power the modem on and off. For early versions of the shield, it was necessary to press the power button to turn on the modem. Newer versions of the board will turn the modem on automatically.
If you have an early version of the shield, and it does not turn on automatically, you can solder a jumper to the CTRL/D7 pad on the reverse side of the board, and it will turn on when an attached Arduino receives power.
Several of the modem pins are exposed on the underside of the board. These provide access to the modem for features like speaker output and microphone input. See the datasheet for complete information.

Stream Class Functions In Arduino Programming Language

 Stream Functions In Arduino Programming Language:

available()

Description

available() gets the number of bytes available in the stream. This is only for bytes that have already arrived.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.available()

Parameters

stream : an instance of a class that inherits from Stream.

Returns

int : the number of bytes available to read


read()

Description

read() reads characters from an incoming stream to the buffer.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.read()

Parameters

stream : an instance of a class that inherits from Stream.

Returns

the first byte of incoming data available (or -1 if no data is available)


flush()

Description

flush() clears the buffer once all outgoing characters have been sent.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.flush()

Parameters

stream : an instance of a class that inherits from Stream.

Returns

boolean

find()

Description

find() reads data from the stream until the target string of given length is found The function returns true if target string is found, false if timed out.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.find(target)

Parameters

stream : an instance of a class that inherits from Stream.
target : the string to search for (char)

Returns

boolean

findUntil()

Description

findUntil() reads data from the stream until the target string of given length or terminator string is found.
The function returns true if target string is found, false if timed out
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.findUntil(target, terminal)

Parameters

stream : an instance of a class that inherits from Stream.
target : the string to search for (char)
terminal : the terminal string in the search (char)

Returns

boolean

peek()

Read a byte from the file without advancing to the next one. That is, successive calls to peek() will return the same value, as will the next call to read().
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.peek()

Parameters

stream : an instance of a class that inherits from Stream.

Returns

The next byte (or character), or -1 if none is available.


readBytes()

Description

readBytes() read characters from a stream into a buffer. The function terminates if the determined length has been read, or it times out (see setTimeout()).
readBytes() returns the number of characters placed in the buffer. A 0 means no valid data was found.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.readBytes(buffer, length)

Parameters

stream : an instance of a class that inherits from Stream.
buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)

Returns

byte


readBytesUntil()

Description

readBytesUntil() read characters from a stream into a buffer. The function terminates if the terminator character is detected, the determined length has been read, or it times out (see setTimeout()).
readBytesUntil() returns the number of characters placed in the buffer. A 0 means no valid data was found.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.readBytesUntil(character, buffer, length)

Parameters

stream : an instance of a class that inherits from Stream.
character : the character to search for (char)
buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)

Returns

byte



parseInt()

Description

parseInt() returns the first valid (long) integer number from the current position. Initial characters that are not integers (or the minus sign) are skipped. parseInt() is terminated by the first character that is not a digit.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.parseInt(list)

Parameters

stream : an instance of a class that inherits from Stream.
list : the stream to check for ints (char)

Returns

int



parseFloat()

Description

parseFloat() returns the first valid floating point number from the current position. Initial characters that are not digits (or the minus sign) are skipped. parseFloat() is terminated by the first character that is not a floating point number.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.parseFloat(list)

Parameters

stream : an instance of a class that inherits from Stream.
list : the stream to check for floats (char)

Returns

float



setTimeout()

Description

setTimeout() sets the maximum milliseconds to wait for stream data, it defaults to 1000 milliseconds. This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class main page for more information.

Syntax

stream.setTimeout(time)

Parameters

stream : an instance of a class that inherits from Stream.
time : timeout duration in milliseconds (long).

Parameters

None

Stream Class Of Aduino Programming Language

Stream


Stream is the base class for character and binary based streams. It is not called directly, but invoked whenever you use a function that relies on it.
Stream defines the reading functions in Arduino. When using any core functionality that uses a read() or similar method, you can safely assume it calls on the Stream class. For functions like print(), Stream inherits from the Print class.
Some of the libraries that rely on Stream include :
  • Serial
  • Wire
  • Ethernet Client
  • Ethernet Server
  • SD

 

Functions

  • available()
  • read()
  • flush()
  • find()
  • findUntil()
  • peek()
  • readBytes()
  • readBytesUntil()
  • parseInt()
  • parsefloat()
  • setTimeout()

Interfacing RF Shield/Module In Arduino

Simplified Block Diagram Of A Radio Frequency Communication System
Simplified Block Diagram Of A Radio Frequency Communication System
A simplified Radio Frequency communication block diagram is shown above. Since most of the encoders/decoders/microcontrollers are TTL compatible, most of the inputs by the user will be given in TTL logic level. Thus, this TTL input is to be converted into serial data input using an encoder or a microcontroller. This serial data can be directly read using the RF Transmitter, which then performs ASK (in some cases FSK or PSK) modulation on it and transmit the data through the antenna.

In the receiver side, the RF Receiver receives the modulated signal through the antenna, performs all kinds of processing, filtering, demodulation, etc and gives out a serial data. This serial data is then converted to a TTL level logic data, which is the same data that the user has input.

RF module
An RF Module (Radio Frequency Module) is a small electronic circuit used to transmit and/or receive radio signals on one of a number of carrier frequencies. RF Modules are widely used in electronic design owing to the difficulty of designing radio circuitry. RF Modules are most often used in medium and low volume products for consumer applications such as garage door openers, wireless alarm systems, industrial remote controls, smart sensor applications, and wireless home automation systems. This has single channel for data transfer, thus serial data communication is used.
The operating frequency of RF module can be varied. For short range wireless control applications, an ASK RF Transmitter-Receiver Module of frequency 315 MHz or 433 MHz is most suitable. They are quite compact and cheap! You can buy them from various internet stores.
RF Transmitter-Receiver Module
RF Transmitter-Receiver Module
RF Transmitter-Receiver Module
RF Transmitter-Receiver Module
  
Tx Module Pin description:
Pin No
Function
Name
1
Antenna
ANT
2
Serial data input pin
Output
3
Ground(0V)
Ground
4
Supply voltage(3V-12V)
Vcc
 

Rx module Pin description:
Pin No
Function
Name
1
Ground(0V)
Ground
2-3
Serial data output pin
Input
4
Supply voltage(3.3V-6V)
Vcc
5
Antenna
Ant


Connection of RF module and Arduino is very simple, in market you can find many one that are compatible with Arduino.
Rx/Tx Connections
Rx/Tx Connections
Transmitter Schematic
Transmitter Schematic
In schematic you can find Arduino Board, which is denoted by U1. You can see some buttons at the right side of the Schematic. This button is used for general purpose.  There are 5 switches, you can use it like up, down, left, right and enter. And according to these buttons you need to send data through Tx module. Here Tx module connector  is denoted by TX. At the upper left side of the schematic you can notice that we have put a seven segment display which is CC(Common Cathode)type. When a switch is pressed,the corresponding switch number (1,2,3,4,5) will be shown in seven segment display. For controlling seven segment displays we have used 7447 BCD to Seven segment drivers IC. For 7447 datasheet you can click this link. Datasheet of 7447.
Receiver Schematic
Receiver Schematic
In schematic you can find Arduino board which is U1, RF receiver connector which is mention as RF RECEIVER. Here I have connected  two relays for other works. Suppose you want to control two electrical loads by RF transmitter (Ex: RF Remote control).  Here you can notice that D9 & D10 are mentioned as Relay1 and Relay2. By these two pins you can control the relays. The main theme is you get data from RF receiver then you need to check it with your predefined data. If it matches, then you can do anything you want.

Connection procedure
  • First you need to connect your Transmitter shield with an Arduino board and also a Receiver shield with another Arduino Board.
  • Plug 12V Dc with both of the Arduino Boards so that Arduino can start working.
  • If you think, you don’t want to use our Rx, Tx module then you need to connect wire properly between Tx, Rx module and also shield. You don’t need to be worried about this. By shield you also can connect other Tx, Rx module with Arduino. For Schematic please check the link:
  • Now your circuit setup is complete.
  • For coding you need to  plug Usb cable with your Arduino.
  • Now start your code and debug. Enjoy!!!
Coding
To send data you need to synchronize your Tx and Rx module. For this you need to send 0’b01010101 or ‘U’ which  has a binary value 01010101. This is called pre-amble. This pre-amble byte is usually sent 2 to 5 times in a row to synchronize sender and receiver, BUT NOT ALWAYS! Once you have synchronized your chip to the RF receiver you can sample the bits “in the middle” of your data line. In your data you also need to attach starting bit and ending bit, without these two bits you can’t understand when the main data is started and when finished. Data pattern can be like this:  "UUU/Arduino Rocks#@". In this data pattern you can notice that at first I have sent ‘U’ 3 times for synchronization and after that I have put the start bit by ‘/’ and then sent data which is "Arduino Rocks" and finally sending finish bit by "#@ ".


Code for Receiver module

#include <SoftwareSerial.h>      // Include Software Serial libary
SoftwareSerial mySerial(4,6);    // Rx,Tx
//===========Scan function=================================
void scan()
{
//=================Variable Initialization================//
char tmp[20];
char data[20];
for(int i=0;i<20;i++)// Every Index Initialize by 0
{
tmp[i]=0;
}
byte len=0;
//========================================================//
//===============Algorithm Start=========================//
if(mySerial.available())  // If Software Serial detect any data in it's buffer
{
mySerial.setTimeout(10000);// Set timeout for 10 sec
mySerial.flush();          // Flush MySerial buffer
// This is build in function of Software serial
// findUntil() reads data from the stream until the target string
// of given length or terminator string is found.
// The function returns true if target string is found, false if timed out
// Syntax:   stream.findUntil(target, terminal)
// Sending Data pattern would be in this example: UUU/PiLabs*@
// Sending Data pattern must be: /USER DEFGINED DATA*@
if(mySerial.findUntil("@","@"))//checking the condition
{
// readBytesUntil() read characters from a stream into a buffer. The function
// terminates if the terminator character is detected, the determined length has been read,
// or it times out.
// readBytesUntil() returns the number of characters placed in the buffer. A 0 means no valid data was found.
// Syntax:   stream.readBytesUntil(character, buffer, length)
len= mySerial.readBytesUntil('@',tmp,50);// From this instruction we can get length of the string
// Also saved the string in tmp
Serial.println(tmp);                    // For Debugging we print tmp string in serial port
Serial.println(len);                    // For debugging we print the length of string
int i=0;                                // Initialize variable i
for(i=0;i<20;i++)                       // in here data's every index initialize by 0
{
data[i]=0;
}
// ===Algorithm for Sorting main data from Total String======
while(tmp[i]!='*')                      // Searching for * Because Main data start after *
{
i++;                                  // Increamented index by 1
}
i++;                                    // When * is found index increase 1 bcoz main data start
// after *
int j=0;                                // Initialize j by 0
 while(tmp[i]!='/')                      // Now its searching for '/' And till '/' its stored data in data variable
{
data[j]=tmp[i];   // Stored data in data variable from string
i++;                                 // Increament index
j++;                                 // Increament index
}
Serial.println(data);   // Serial data print in serial terminal
// strcmp is a function which return 0 when two string match
if(strcmp("PiLabs,Rock",data)==0)
{                 // And in here it checked by strcmp function
Serial.println("GOTCHA");            // Serial Printout
}
}
}
}
//================Setup function=============================================
void setup()
{
Serial.begin(9600);     // Serial Port initialization by 9600 Bps
mySerial.begin(1200);//SoftwareSerial port initialization by 1200 bps
mySerial.setTimeout(10000);      // Set time out 10 sec
mySerial.flush();                // Software serial buffer flush
}
//=================loop Function====================================
void loop()
{
scan();                // Called scan function
}

Code for Transmitter module

#include <SoftwareSerial.h>      // Include Software Serial libary
SoftwareSerial mySerial(6,7);    // Rx,Tx
//=======================================================
//============show__segment function =========================
//=======================================================
void show__segment(int button__no)// Show__segment function start
{
if(button__no==0)// if button no 0 is pressed
{
digitalWrite(2,LOW);// 0|
digitalWrite(3,LOW);// 0|
digitalWrite(4,LOW);// 0|so no is 0
digitalWrite(5,LOW);// 0|
mySerial.println("UUU/PiLabsON0*@");// Data send via mySerial
}
else if(button__no==1) //if button no 1 is pressed
{
digitalWrite(2,HIGH);// 1|
digitalWrite(3,LOW);//  0|
digitalWrite(4,LOW);//  0|so no is 1
digitalWrite(5,LOW);//  0|
mySerial.println("UUU/PiLabsON1*@");// Data send via mySerial
}
else if(button__no==2)//if button no 2 is pressed
{
digitalWrite(2,LOW);//  0|
digitalWrite(3,HIGH);// 1|
digitalWrite(4,LOW);//  0|so no is 2
digitalWrite(5,LOW);//  0|
mySerial.println("UUU/PiLabsON2*@");// Data send via mySerial
}
else if(button__no==3)//if button no 3 is pressed
{
digitalWrite(2,HIGH);// 1
digitalWrite(3,HIGH);// 1
digitalWrite(4,LOW);//  0 So no is 3
digitalWrite(5,LOW);//  0
mySerial.println("UUU/PiLabsON3*@");// Data send via mySerial
}
else if(button__no==4)//if button no 4 is pressed
{
digitalWrite(2,LOW);//  0|
digitalWrite(3,LOW);//  0|
digitalWrite(4,HIGH);// 1|so no is 4
digitalWrite(5,LOW);//  0|
mySerial.println("UUU/PiLabsON4*@");// Data send via mySerial
}
}
//=======================================================
//=============== Scan__button function =======================
//=======================================================
void scan__button()// Scan__button function start
{
if(digitalRead(12)== LOW)// Checking 12 no pin for button press
{
show__segment(1);  // show__segment function call for no:1
}
else if(digitalRead(10)== LOW)// Checking 10 no pin for button press
{
show__segment(2);// show__segment function call for no:2
}
else if(digitalRead(9)== LOW)// Checking 9 no pin for button press
{
show__segment(3);// show__segment function call for no:3
}
else if(digitalRead(8)== LOW)// Checking 8 no pin for button press
{
show__segment(4); // show__segment function call for no:4
}
}
//=========================================================
//=================== Setup==================================
//============================================================
void setup()
{
pinMode(2,OUTPUT);//Define output, this pin is for A of 7447
pinMode(3,OUTPUT);//Define output, this pin is for B of 7447
pinMode(4,OUTPUT);//Define output, this pin is for C of 7447
pinMode(5,OUTPUT);//Define output, this pin is for D of 7447
pinMode(8,INPUT);//Define input
digitalWrite(8, HIGH);// Pull Up enable
pinMode(9,INPUT);//Define input
digitalWrite(9, HIGH);//Pull Up enable
pinMode(10,INPUT);//Define input
digitalWrite(10, HIGH);//Pull Up enable
pinMode(11,INPUT);//Define input
digitalWrite(11, HIGH);//Pull Up enable
pinMode(12,INPUT);//Define input
digitalWrite(12, HIGH);//Pull Up enable
Serial.begin(9600);                        // Serial Port initialization by 9600 Bps
jgkc
mySerial.begin(1200);                      // Software Serial port initialization by 1200 bps
mySerial.setTimeout(10000);                // Set time out 10 sec
mySerial.flush();                          // Software serial buffer flush
show__segment(0); // By default it shows 0
}
//========================================================
//==================== loop=================================
//========================================================
void loop()
{
scan__button();// scan__button function call
}

In above code we used some Arduino’s special function which are:
  • findUntil()
  • readBytesUntil()


findUntil()

 

Description

findUntil() reads data from the stream until the target string of given length or terminator string is found.
The function returns true if target string is found, false if timed out
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class page for more information.

Syntax

stream.findUntil(target, terminal)

Parameters

stream : an instance of a class that inherits from Stream.
target : the string to search for (char)
terminal : the terminal string in the search (char)

Returns

boolean

readBytesUntil()

 

Description

readBytesUntil() read characters from a stream into a buffer. The function terminates if the terminator character is detected, the determined length has been read, or it times out (see setTimeout()).
readBytesUntil() returns the number of characters placed in the buffer. A 0 means no valid data was found.
This function is part of the Stream class, and is called by any class that inherits from it (Wire, Serial, etc). See the Stream class page for more information.

Syntax

stream.readBytesUntil(character, buffer, length)

Parameters

stream : an instance of a class that inherits from Stream.
character : the character to search for (char)
buffer: the buffer to store the bytes in (char[] or byte[])
length : the number of bytes to read (int)

Returns

byte