Click here to Skip to main content
Click here to Skip to main content

Send and Read SMS through a GSM Modem using AT Commands

By , 30 Aug 2010
 

Introduction

There are many different kinds of applications SMS applications in the market today, and many others are being developed. Applications in which SMS messaging can be utilized are virtually unlimited. Some common examples of these are given below:

  • Person-to-person text messaging is the most commonly used SMS application, and it is what the SMS technology was originally designed for.
  • Many content providers make use of SMS text messages to send information such as news, weather report, and financial data to their subscribers.
  • SMS messages can carry binary data, and so SMS can be used as the transport medium of wireless downloads. Objects such as ringtones, wallpapers, pictures, and operator logos can be encoded in SMS messages.
  • SMS is a very suitable technology for delivering alerts and notifications of important events.
  • SMS messaging can be used as a marketing tool.

In general, there are two ways to send SMS messages from a computer / PC to a mobile phone:

  1. Connect a mobile phone or GSM/GPRS modem to a computer / PC. Then use the computer / PC and AT commands to instruct the mobile phone or GSM/GPRS modem to send SMS messages.
  2. Connect the computer / PC to the SMS center (SMSC) or SMS gateway of a wireless carrier or SMS service provider. Then send SMS messages using a protocol / interface supported by the SMSC or SMS gateway.

In this article, I will explain the first way to send, read, and delete SMS using AT commands. But before starting, I would like to explain a little bit about AT commands.

AT Commands

AT commands are instructions used to control a modem. AT is the abbreviation of ATtention. Every command line starts with "AT" or "at". That's why modem commands are called AT commands. There are two types of AT commands:

  1. Basic commands are AT commands that do not start with a "+". For example, D (Dial), A (Answer), H (Hook control), and O (Return to online data state) are the basic commands.
  2. Extended commands are AT commands that start with a "+". All GSM AT commands are extended commands. For example, +CMGS (Send SMS message), +CMGL (List SMS messages), and +CMGR (Read SMS messages) are extended commands.

If you want to get more information about AT commands, then you can get it on my other article on CodeProject here: http://www.codeproject.com/KB/system/IntroductiontoATcommands.aspx.

Operating Modes

The SMS specification has defined two modes in which a GSM/GPRS modem or mobile phone can operate. They are called SMS text mode and SMS PDU mode. (PDU stands for Protocol Data Unit.) The mode that a GSM/GPRS modem or mobile phone is operating in determines the syntax of some SMS AT commands and the format of the responses returned after execution.

I am using SMS text mode in this article.

How to Test GSM Modem Connectivity Using Hyper Terminal

  • First, find the best GSM modem that suits the needs. I tested this application with a Wavecom FASTRACK M1206.
  • Understand the AT Command set required to communicate with the modem.
  • Connect the modem to the computer according to the setup guide specified in the manual provided with the GSM modem.
  • Put a valid SIM card into the mobile phone or GSM/GPRS modem.
  • Connect your mobile phone or GSM/GPRS modem to a computer, and set up the corresponding wireless modem driver.
  • Run the MS HyperTerminal by selecting Start -> Programs -> Accessories -> Communications -> HyperTerminal.
  • In the Connection Description dialog box, enter a name and choose an icon you like for the connection. Then click the OK button.
  • In the Connect To dialog box, choose the COM port that your mobile phone or GSM/GPRS modem is connecting to in the Connect using combo box. For example, choose COM1 if your mobile phone or GSM/GPRS modem is connecting to the COM1 port. Then click the OK button.
  • The Properties dialog box comes out. Enter the correct port settings for your mobile phone or GSM/GPRS modem. Then click the OK button.
  • To find the correct port settings that should be used with your mobile phone or GSM/GPRS modem, consult the manual of your mobile phone or GSM/GPRS modem.
  • Type "AT" in the main window. A response "OK" should be returned from the mobile phone or GSM/GPRS modem.
  • If “OK” returns, it means your mobile phone or GSM/GPRS modem is connected successfully.

After successful connection of the GSM /GPRS modem with PC, you are ready to run this application. Download the attached project and run the application.

Sending SMS through GSM Modem using AT Commands

Port Settings

In this tab, you will have to do port settings which will be the same as you did in the hyper terminal and then click the OK button. If the modem is connected successfully, a message box will appear with the message “Modem is connected”.

public SerialPort OpenPort(string p_strPortName,
       int p_uBaudRate, int p_uDataBits, 
       int p_uReadTimeout, int p_uWriteTimeout)
{
    receiveNow = new AutoResetEvent(false);
    SerialPort port = new SerialPort();

    try
    {
        port.PortName = p_strPortName;                 //COM1
        port.BaudRate = p_uBaudRate;                   //9600
        port.DataBits = p_uDataBits;                   //8
        port.StopBits = StopBits.One;                  //1
        port.Parity = Parity.None;                     //None
        port.ReadTimeout = p_uReadTimeout;             //300
        port.WriteTimeout = p_uWriteTimeout;           //300
        port.Encoding = Encoding.GetEncoding("iso-8859-1");
        port.DataReceived += new SerialDataReceivedEventHandler
                (port_DataReceived);
        port.Open();
        port.DtrEnable = true;
        port.RtsEnable = true;
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return port;
}

Send SMS

In the second tab, you can send SMS:

public bool sendMsg(SerialPort port, string PhoneNo, string Message)
{
    bool isSend = false;

    try
    {
        string recievedData = ExecCommand(port,"AT", 300, "No phone connected");
        recievedData = ExecCommand(port,"AT+CMGF=1", 300,
            "Failed to set message format.");
        String command = "AT+CMGS=\"" + PhoneNo + "\"";
        recievedData = ExecCommand(port,command, 300,
            "Failed to accept phoneNo");
        command = Message + char.ConvertFromUtf32(26) + "\r";
        recievedData = ExecCommand(port,command, 3000,
            "Failed to send message"); //3 seconds
        if (recievedData.EndsWith("\r\nOK\r\n"))
        {
            isSend = true;
        }
        else if (recievedData.Contains("ERROR"))
        {
            isSend = false;
        }
        return isSend;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

Read SMS

In the third tab, you can read SMS:

public ShortMessageCollection ReadSMS(SerialPort port)
{
    // Set up the phone and read the messages
    ShortMessageCollection messages = null;
    try
    {
        #region Execute Command
        // Check connection
        ExecCommand(port,"AT", 300, "No phone connected");
        // Use message format "Text mode"
        ExecCommand(port,"AT+CMGF=1", 300, "Failed to set message format.");
        // Use character set "PCCP437"
        ExecCommand(port,"AT+CSCS=\"PCCP437\"", 300,
        "Failed to set character set.");
        // Select SIM storage
        ExecCommand(port,"AT+CPMS=\"SM\"", 300,
        "Failed to select message storage.");
        // Read the messages
        string input = ExecCommand(port,"AT+CMGL=\"ALL\"", 5000,
            "Failed to read the messages.");
        #endregion

        #region Parse messages
        messages = ParseMessages(input);
        #endregion
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }

    if (messages != null)
        return messages;
    else
        return null;
}

Delete SMS

In the fourth and last tab, you can count the number of SMS and delete SMS as well.

public bool DeleteMsg(SerialPort port , string p_strCommand)
{
    bool isDeleted = false;
    try
    {
        #region Execute Command
        string recievedData = ExecCommand(port,"AT", 300, "No phone connected");
        recievedData = ExecCommand(port,"AT+CMGF=1", 300,
            "Failed to set message format.");
        String command = p_strCommand;
        recievedData = ExecCommand(port,command, 300, "Failed to delete message");
        #endregion

        if (recievedData.EndsWith("\r\nOK\r\n"))
        {
            isDeleted = true;
        }
        if (recievedData.Contains("ERROR"))
        {
            isDeleted = false;
        }
        return isDeleted;
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

Points of Interest

I'm not using any third party library or anything else in this project.

History

  • 4th August, 2009: Initial post.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Syeda Anila Nusrat
Software Developer Syndustria Pvt Ltd
Pakistan Pakistan
Name: Syeda Anila Nusrat
 
Education:-
National University of Computer and Emerging Sciences
MS (Computer Science) 2010–2012 (expected)
Federal Urdu University of Arts, Science and Technology
BS (Computer Science) 2004–2007
 
Professional Experience:-
Software Engineer at Syndustria Pvt Ltd (Jun2008-Feb2010)
Software Engineer(internee) at yEvolve Pvt Ltd (Feb2008-Apr 2008)
 
Specialties:-
IDE: Ms Visual Studio 2005 and 2008
Programming Languages: C++.NET, C#.NET, VB.NET, ADO.NET
Web Technologies: ASP.NET, AJAX, Html, CSS, Java Scripting
Databases: SQL Server 2000, SQL Server 2005
Programming Methodologies: Multithreading and DLLs
Scheduling and Modeling tools: Ms-Project 2000, MS Visio, Rational Rose
 
Honors and Awards:-
Received Merit Certificate for scoring 3.81 CGPA on scale of 4.0 in BS(CS)
 
My professional Network
http://pk.linkedin.com/in/syedaanila

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAfter delete message, Read Message won't work properlymemberwynnt3o12327-Aug-12 19:00 
After I delete all message, and I resent one message to the phone, now the mesage cant shown after clicked read message. It might due to the listview problem?
QuestionError: Response received is incomplete but still send SMS Message successfully???memberbonfirebmt15-Aug-12 1:04 
hi,
i used your application to send SMS Message , sometime it appears Error: "Response received is incomplete" while I still receive the SMS Message successfully.
Why?
I use a GPRS Modem (WeaveCom) with USB Port.
AnswerRe: Error: Response received is incomplete but still send SMS Message successfully???memberfatihuyaroglu1-May-13 20:27 
set timeout to 4000 or 5000 while sending message at command
this can help you, but i am not sure %100
recievedData = ExecCommand(port, command, 4000, "Failed to send message"); //4 seconds
or
recievedData = ExecCommand(port, command, 5000, "Failed to send message"); //5 seconds
QuestionApplication Is not workingmemberMohit_Patel9-Aug-12 2:59 
Dear Miss.
 
Using your application I tried to send SMS but unfortunately Error comes which is like (No SMS Found in SIM).
please Help Me
 
Thanks & Regards,
--
Mohit Patel

Questionhi!memberroylandrix1-Aug-12 23:15 
hello. . . .can you please send to me the code . . this is my email address. .roylandrix@gmail.com
Questionhmmmm she is not a good developermemberAziz BUkhari24-Jul-12 10:57 
she is a developer not a programmer... gpa is not necessary for developement Smile | :)
and this project is not her that is cracked bye her ..... every developer is not a good programmer but every programmer is a good developer Smile | :)
QuestionHyperterminal substitutememberAnand scientist23-Jul-12 19:07 
Is there is any substitute for Hyperterminal as it is not in Win 7.
AnswerRe: Hyperterminal substitutememberGreyham13-Sep-12 11:05 
You can copy Hyperterminal from Windows XP and run it ok in Windows 7.
QuestionCan't Send SMSmemberSupraKing23-Jul-12 15:31 
I can't send a sms and can't read sms too
Questionunable to read smsmemberaa007122345523-Jun-12 12:12 
if (receiveNow.WaitOne(timeout, false)
 
Hi,First of all great work and thanks for sharing the stuff.
 
As I am begineer in this sms and serial port coding but I have a serial port modem.and I am able to connect with your software perfectly but..
when i try to read the sms from my sim then there is a if loop
if (receiveNow.WaitOne(timeout, false)
 
there it will eventually go in else part and log the report...
I am unable to understand that why it is reacting like that ...I tried to reserach on this command and class but unable to understand the things..is it waiting for any signal or so..and i am sure that my modem and sim is working perfectly as i have another system where the same modem and sim is working fine...
 
SO please help me out i want to use your peice of code...
thanks in advance...
 
Regards
Mahendra
GeneralMy vote of 3memberMr Pham1-Jun-12 21:20 
do not receive new message automatically
GeneralRe: My vote of 3memberwaqas7867522-Dec-12 0:31 
i cant able to read sms kindly help me out , its related to my project , i cant able to find any help
QuestionNot able Reading SMSmembersaleem muhammad30-May-12 22:40 
Dear Miss.
M trying ur software for read sms from nokia 6710. but it cant read sms. And the Error is (No SMS Found in SIM) please Hel Me this is very important for me
Thanks
QuestionMessage reading errormemberMember 804117824-May-12 18:58 
The sending part is worked. But the receiving part is not working. plz help me. it is urgent for me....
Questiondelivery reportmemberdanar_kalari22-May-12 3:43 
can i get delivery report please help
Question"recieveNow" does not exist in the current context.memberaliiiakbar13-May-12 0:58 
Hello every one, I am having this error while compiling
 
"The name 'recieveNow does now exist in the current context'".
Please Help!!
QuestionC# Listener to detect new smsmemberdeep19313-May-12 20:34 
hi.. i developing a web application using c# to send and receive sms, sending receiveing is working fine, but receiving of sms i working on button click event, but i want whenever new sms comes program should show it automatically...
Please help me...
Thanks
QuestionHow to connect to modem via IPmemberamilapradeep28-Apr-12 23:32 
i have the same requirement for my project and but the modem i have is connected to machine via IP. it does not have port to connect to com port. i can send and receive sms via the interface which device provide. (by typing the IP)
 
but i don't have an idea how i should communicate with modem to send AT commands. i tried by creating TCP/IP stream and write the stream to it. even though it is successfully runs, nothing happens. (no SMS sending)
 
Please help me. i,m sucked here for a day.
QuestionMy Vote - GreatmemberMember 197994416-Apr-12 1:49 
Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
GeneralMy vote of 5memberaduchiuchiu11-Apr-12 21:48 
Very nice
QuestionERROR 515memberronaldlearnC7-Apr-12 16:19 
i get conected but ican't send de mesage to my phone .. my phone model is LG GM205 do you know if AT comands are suport for this models? i got the mesage ...Response recived incomplete, for last i put this info in my SIM textbox (on aplication runing) --> +591472886297 ..+591 code for BOLIVIA ..4 area Code and my cellphone number 72886297 is this info wrong ? wht would probably be the main error?? any idea? and sorry my english i'm learning.
AnswerRe: ERROR 515memberMember 443119322-Apr-12 18:30 
CMS ERROR: 514 Invalid Status
 
source: http://code.google.com/p/smslib/wiki/GSM_Errors[^]
QuestionGSM Modem using AT CommandsmemberMember 876064726-Mar-12 0:22 
pls tell me how to get sms to mysql database...?
QuestionNo SuccessmemberFarhan7522-Mar-12 9:34 
Tried this app, but can't send sms, my phone does get connected at COM port, but no reply from phone.
QuestionHow to Send SMS more than 160 Character ?memberPatil Kishor14-Mar-12 19:54 
How to send sms more than 160 character using at command? and which commands are used to send,Please reply me.. Wink | ;)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web01 | 2.6.130617.1 | Last Updated 30 Aug 2010
Article Copyright 2009 by Syeda Anila Nusrat
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid