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

How To Send and Receive SMS using GSM Modem

By , 10 Sep 2007
 
Screenshot - MainScreen.jpg

Introduction

SMS client and server is an application software which is used for sending and receiving messages(SMS). It listens for incoming messages to arrive, processes the message if it's in a valid format. Note the processing of arrived messages depends on the application which will be discussed later. I am going to explain the following things:

  1. Communication Port Settings
  2. Receive Incoming Message
  3. Send Messages
  4. Read All Messages (Sent by the users)
  5. Delete Messages (One or All)

I have used the GSMComm Library for Sending and Receiving SMS. You require a GSM modem or phone for sending an SMS.

Using the code

1) Communication Port Settings

Screenshot - CommSettings.jpg

CommSetting class is used for storing comm port settings:

public class CommSetting
{
    public static int Comm_Port=0;
    public static Int64 Comm_BaudRate=0;
    public static Int64 Comm_TimeOut=0;
    public static GsmCommMain comm;

    public CommSetting()
    {
        //
        // TODO: Add constructor logic here
        //
    }
}

Comm is an object of type GsmCommMain which is required for sending and receiving messages. We have to set the Comm port, Baud rate and time out for our comm object of type GsmCommMain. Then try to open with the above settings. We can test the Comm port settings by clicking on the Test button after selecting the Comm port, baud rate and Time out. Sometimes if the comm port is unable to open, you will get a message "No phone connected". This is mainly due to Baud rate settings. Change the baud rate and check again by clicking the Test button until you get a message "Successfully connected to the phone."

Before creating a GSMComm object with settings, we need to validate the port number, baud rate and Timeout.

The EnterNewSettings() does validation, returns true if valid, and will invoke SetData(port,baud,timeout) for comm setting.

The following block of code will try to connect. If any problem occurs "Phone not connected" message appears and you can either retry by clicking on the Retry button or else Cancel.

GsmCommMain comm = new GsmCommMain(port, baudRate, timeout);
try
{
        comm.Open();
        while (!comm.IsConnected())
        {
            Cursor.Current = Cursors.Default;
            if (MessageBox.Show(this, "No phone connected.",
               "Connection setup", MessageBoxButtons.RetryCancel,
                 MessageBoxIcon.Exclamation) == DialogResult.Cancel)
            {
                comm.Close();
                return;
            }
            Cursor.Current = Cursors.WaitCursor;
        }

        // Close Comm port connection (Since it's just for testing
        // connection)
        comm.Close();
}
catch(Exception ex)
{
    MessageBox.Show(this, "Connection error: " + ex.Message,
    "Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    return;
}

// display message if connection is a success.
MessageBox.Show(this, "Successfully connected to the phone.",
"Connection setup", MessageBoxButtons.OK, MessageBoxIcon.Information);
Screenshot - SucessfullyConnected.jpg

2) Receive Incoming Message

We are going to register the following events for GSMComm object comm.

  1. PhoneConnected
    This event is invoked when you try to open the Comm port. The event handler for Phone connected is comm_PhoneConnected which will invoke OnPhoneConnectionChange(bool connected) with the help of Delegate ConnectedHandler.
  2. MessageReceived
    This event is invoked when a message arrives at the GSM phone. We will register with MessageReceivedEventHandler. When the incoming message arrives, the comm_MessageReceived method will be invoked which in turn calls the MessageReceived() method in order to process the unread message. GSMComm object comm has a method ReadMessages which will be used for reading messages. It accepts the following parameters phone status (All, ReceivedRead, ReceivedUnread, StoredSent, and StoredUnsent) and storage type: SIM memory or Phone memory.
private void MessageReceived()
{
    Cursor.Current = Cursors.WaitCursor;
    string storage = GetMessageStorage();
    DecodedShortMessage[] messages = CommSetting.comm.ReadMessages
                   (PhoneMessageStatus.ReceivedUnread, storage);
    foreach(DecodedShortMessage message in messages)
    {
         Output(string.Format("Message status = {0},
     Location =  {1}/{2}",
         StatusToString(message.Status),
         message.Storage, message.Index));
         ShowMessage(message.Data);
         Output("");
    }

    Output(string.Format("{0,9} messages read.",
                messages.Length.ToString()));
    Output("");
}   

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message.

3) Send Message

Screenshot - SendSMS.jpg

You can send an SMS by keying in the destination phone number and text message.

If you want to send a message in your native language (Unicode), you need to check in Send as Unicode(UCS2). GSMComm object comm has a SendMessage method which will be used for sending SMS to any phone. Create a PDU for sending messages. We can create a PDU in straight forward version as:

SmsSubmitPdu pdu = new SmsSubmitPdu
        (txt_message.Text,txt_destination_numbers.Text,"");

An extended version of PDU is used when you are sending a message in Unicode.

 try
{
    // Send an SMS message
    SmsSubmitPdu pdu;
    bool alert = chkAlert.Checked;
    bool unicode = chkUnicode.Checked;

    if (!alert && !unicode)
    {
        // The straightforward version
        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text,"");
    }
    else
    {
        // The extended version with dcs
        byte dcs;
        if (!alert && unicode)
            dcs = DataCodingScheme.NoClass_16Bit;
        else
        if (alert && !unicode)
            dcs = DataCodingScheme.Class0_7Bit;
        else
        if (alert && unicode)
            dcs = DataCodingScheme.Class0_16Bit;
        else
            dcs = DataCodingScheme.NoClass_7Bit;

        pdu = new SmsSubmitPdu
        (txt_message.Text, txt_destination_numbers.Text, "", dcs);
    }

    // Send the same message multiple times if this is set
        int times = chkMultipleTimes.Checked ?
                int.Parse(txtSendTimes.Text) : 1;

    // Send the message the specified number of times
    for (int i=0;i<times;i++)
    {
        CommSetting.comm.SendMessage(pdu);
        Output("Message {0} of {1} sent.", i+1, times);
        Output("");
    }
}
catch(Exception ex)
{
    MessageBox.Show(ex.Message);
}

Cursor.Current = Cursors.Default;

4) Read All Messages

Screenshot - ReadAllMessages.jpg

You can read all messages from the phone memory of SIM memory. Just click on "Read All Messages" button. The message details such as sender, date-time, text message will be displayed on the Data Grid. Create a new row for each read message, add to Data table and assign the Data table to datagrid's source

private void BindGrid(SmsPdu pdu)
{
    DataRow dr=dt.NewRow();
    SmsDeliverPdu data = (SmsDeliverPdu)pdu;

    dr[0]=data.OriginatingAddress.ToString();
    dr[1]=data.SCTimestamp.ToString();
    dr[2]=data.UserDataText;
    dt.Rows.Add(dr);

    dataGrid1.DataSource=dt;
}

The above code will read all unread messages from SIM memory. The method ShowMessage is used for displaying the read message. The message may be a status report, stored message sent/un sent, or a received message. The only change in processing Received message and Read message is the first parameter.

For received message

DecodedShortMessage[] messages =
  CommSetting.comm.ReadMessages(PhoneMessageStatus.ReceivedUnread, storage);

For read all messages

DecodedShortMessage[] messages =
   CommSetting.comm.ReadMessages(PhoneMessageStatus.All, storage);

5) Delete Messages (One or All)

Screenshot - DeleteMessage.jpg

All messages which are sent by the users will be stored in SIM memory and we are going to display them in the Data grid. We can delete a single message by specifying the message index number. We can delete all messages from SIM memory by clicking on "Delete All" button. Messages are deleted based on the index. Every message will be stored in memory with a unique index.

The following code will delete a message based on index:

// Delete the message with the specified index from storage
CommSetting.comm.DeleteMessage(index, storage);

To delete all messages from memory( SIM/Phone)

// Delete all messages from phone memory
CommSetting.comm.DeleteMessages(DeleteScope.All, storage); 

The DeleteScope is an Enum which contains:

  1. All
  2. Read
  3. ReadAndSent
  4. ReadSentAndUnsent

Applications

Here are some interesting applications where you can use and modify this software.

1) Pre paid Electricity

Scenario (Customer)

The customer has agreed for pre paid electricity recharges with the help of recharge coupons. The coupon is made available at shops. The customer will first buy the coupons from shops; every coupon consists of Coupon PIN which will be masked, the customer needs to scratch to view the PIN number. The customer will send an SMS to the SMS Server with a specified message format for recharging.

Message Format for Recharging:
RECHARGE <Coupon No> <Customer ID>

Scenario (Server Database)

On the Server, the Database consists of Customer information along with his telephone number, there will a field named Amount which will be used and updated when the customer recharged with some amount. This application becomes somewhat complex, an automatic meter reading software along with hardware needs to be integrated with this. Automatic meter reading systems will read all meter readings and calculate the amount to be deducted for the customer.

2) Astrology

You can implement as astrology software. The user will send an SMS with his zodiac sign. The SMS server will maintain an Astrology Database with zodiac sign and a text description which contains a message for the day. The Database is required to be updated daily for all zodiac signs.

Message Format which will be used by the user to get message of the day:
Zodiac Sign

3) Remote Controlling System

We can implement a remote controlling system, for example you need to:

  1. Shutdown
  2. Restart
  3. Log off system

You can send an SMS. The SMS server will listen and then process the message. Based on the message format sent by the user we can take action.
Example if message format is:
SHUTDOWN
Send to SMS phone number.

Conclusion

This project wouldn't be completed unless I thank the GSMComm Lib developer "Stefan Mayr". I customized my application using this Library. You can download the sample project, library from the web link which I provided under the Reference section.

Reference

License

This article, along with any associated source code and files, is licensed under The Apache License, Version 2.0

About the Author

Ranjan.D
Web Developer
United States United States
Member
No Biography provided

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   
QuestionCMS error 500 PinmemberLe@rner2 May '13 - 1:45 
hi,
 
I am using mobile nokia 200,that is dual sim mobile,while I am sending message in PDU mode its return CMS error 500
 
but when I m sending sms in TEXT mode its working fine,
 
while phone support mode PDU and TEXT mode of sms sending I m checking it using CMGF command.
 
if I use any other device(Nokia E65) its forking fine for PDU mode and TEXT mode.
 
plz help me what can I do for this,
 
thanks.
QuestionConnection error PinmemberNallu Kumarappan28 Apr '13 - 22:21 
Hi,
I'm using HSPA Datacard USB Modem or I need to connect by using any other type of modem. But I'm getting error while connection.
 
Please help me in this issue as much possible.
QuestionNo phone connected PinmemberNallu Kumarappan28 Apr '13 - 20:24 
Hi,
I'm getting error msg as no phone connected.
I'm using gsm modem. I tried all ports & baud rate.
Please help me in this issue.
Nallu

Questioncan't send long arabic sms. Pinmemberhafez28 Apr '13 - 2:38 
Dear All,
I am using GSMCOMM library, I am trying to send long ARABIC SMS in one message.
but it appear on mobile like Chinese or Symbols characters.
Can anyone help me ?
QuestionMessage service error 500 occurred - Error PinmemberMember 996683313 Apr '13 - 0:37 
I am using a Huawei E3131. I am able to receive messages, but when I try to send I get the following error: “Message service error 500 occurred. (GsmComm.GsmCommunication.MessageServiceErrorException). What could be the problem?
QuestionGsmcomm library Pinmembervinod.kande3 Apr '13 - 22:20 
which GSMcomm libray work with this app?
AnswerRe: Gsmcomm library PinmemberRanjan.D4 Apr '13 - 1:32 
GeneralRe: Gsmcomm library Pinmembervinod.kande4 Apr '13 - 2:16 
QuestionNo SIM Pinmemberbalong4131 Mar '13 - 16:06 
How can we make a test if SIM is present. When it executes the get signal function, it goes out to retrieve the correct response from the device but obviously it won't come because there is no SIM card present. It will report after 30000 ms. How can we adjust that time and ouput the correct error like "SIM card Error";
 
thanks
Questionhow send more than 160 character with smartmessagefactory or show me an example ? PinmemberFarhadman25 Feb '13 - 23:16 
Hi Sir
How can I send more than 160 character ? some one said with SmartMessageFactory can do it, but how can I? and can i send arabic(persian) char ?
QuestionQuestion Pinmembernaq_ninetwo9221 Feb '13 - 14:07 
1. Add function which the sms sender(handphone) can receive a status report from GSMComm
 
2. Only restricted phone number can be send sms to the GSMComm
QuestionHelp! PinmemberNainudhiN17 Feb '13 - 20:20 
Hello,
Can I use a USB dongle to connect the sim card to my system for this project?
Please help me out.
Thank you in advance.
Questionsms gsmcomm lib Pinmemberpranavjeet11 Feb '13 - 5:46 
how and where
public static Int16 Comm_Port = 0;
public static Int32 Comm_BaudRate = 0;
public static Int32 Comm_TimeOut = 0;
public static GsmCommMain comm;
to put this code sir,
is
(2)is GSMComm lib is executable file? how to connect modem sir plz plz help... it not identifying
AnswerRe: sms gsmcomm lib PinmemberRanjan.D4 Apr '13 - 1:35 
Questionabout my project Pinmembermitali patil11 Feb '13 - 0:42 
hello sir.... im in final year of engg.... n my projet z electronics based notice board using gsm modem.... but im nt getting the working hw to send sms n hw to get feedback????
AnswerRe: about my project PinmemberRanjan.D11 Feb '13 - 1:25 
GeneralMy vote of 1 Pinmemberhitesh bhatt29 Jan '13 - 1:54 
hh
QuestionMessage notification does not work using a Huawei E372 3G/GSM/USB Modem PinmemberMember 971574422 Jan '13 - 4:31 
Hi,
 
I have a 3G GSM USB Modem by the manufacturer Huawei with the model E372
that I have used for this SMS project. Now everything works in it where
I can send, receive and delete SMS except for the automatic message notifcation.
No matter how many times I send a message from my cell phone to the GSM Modem
it cannot notice the incoming message at all. On the other hand if I use the
software Mobile Partner that can though notice incoming messages on its own.
 
I tried to use the function EnableMessageNotifcations() during the connection
and someone else mentioned about creating a delegate MessageEventHandler but
that did not work either.
 
What could be wrong? Could it be that this GSMComm library does not support
message notifications for this type of modem? Is there any other library
recommended to use?
John T.

QuestionHOW TO SEND A MESSAGE THAT IS MORE THAN 160 CHARACTERS ? PLS HELP THANKS IN ADVANCE Pinmemberehmjhay10 Jan '13 - 22:20 
HI Ranjan,
 
The Program was Great but ofcourse there would be some limitations can you help me out?
i would like to send a message more than 160 characters ..
 
Do we need to have another data coding scheme? by the way i converted the code using VB.NET
 
Thanks,
JAY
AnswerRe: HOW TO SEND A MESSAGE THAT IS MORE THAN 160 CHARACTERS ? PLS HELP THANKS IN ADVANCE Pinmemberhafez8 Feb '13 - 1:59 
QuestionNo Phone's Connected PinmemberLeo Mark Delos Santos18 Dec '12 - 23:16 
Good Day! Sir.
I'm having a problem with the connection though.. it always says "no phone connected".
i'm using a smartbroadband, to send message. perhaps sir,, you can help me with my problem.
SuggestionProblems/Resolutions for this project PinmemberRanjan.D18 Dec '12 - 16:47 
Dear friends,
 
It's being long time sense I worked in this project. As of now I do not have GSM Modem for testing , I'm really sorry and helpless for lot many of you who are facing issues while connecting your phones when you are using this application.
 
I can suggest you with one thing. Just download ILSpy , it's a free opensource di-assembler , then load GSMComm DLL that's the one our project is mainly dependent upon , after loading the assembly you can analyse the source code with in that assembly, also there is an option where you can save code to your local and later you can just analyse the code. Hope it helps you.
 
Thanks,
Ranjan.D

QuestionPhone Not Connected Pinmemberpalesha20 Nov '12 - 3:28 
I have connected nokia 5300 phone successfully.But the program shows Phone not connected. Also d device manager shows the phone connected at COM26 i changed port number in program too. Still shows "Phone Not Connected" Message.
Any Suggestion??
I found this a very nice article.
AnswerRe: Phone Not Connected Pinmemberehmjhay10 Feb '13 - 16:11 
GeneralRe: Phone Not Connected PinmemberRashmitaS4 Apr '13 - 9:19 
GeneralRe: Phone Not Connected PinmemberJ.Mañago10 Apr '13 - 19:24 
QuestionHow to sent sms via xls sheet PinmemberMember 958870010 Nov '12 - 3:44 
1st column is mobile number
2nd column is message text
plz help me.
AnswerRe: How to sent sms via xls sheet PinmemberRanjan.D18 Dec '12 - 16:55 
Questionsend many sms Pinmemberbongdem19038 Nov '12 - 1:37 
now I want to send multiple phone numbers, how to do so
AnswerRe: send many sms PinmemberRanjan.D8 Nov '12 - 1:46 
GeneralMy vote of 5 PinmemberPavan 807768230 Oct '12 - 7:46 
very very good application . simple code.and thank you for giving idea for project. i used this idea for sending notification of immulization
GeneralRe: My vote of 5 PinmemberRanjan.D30 Oct '12 - 8:10 
QuestionPhone Connected but 0 messages read ??? Pinmembermunawersheikh9 Oct '12 - 18:19 
Phone Connected Successfully!
But when reading sms, displays 0 messages read..
AnswerRe: Phone Connected but 0 messages read ??? PinmemberRanjan.D9 Oct '12 - 19:13 
GeneralRe: Phone Connected but 0 messages read ??? Pinmembermunawersheikh10 Oct '12 - 0:43 
GeneralRe: Phone Connected but 0 messages read ??? Pinmemberehmjhay10 Feb '13 - 16:18 
GeneralRe: Phone Connected but 0 messages read ??? PinmemberGlendonz18 Dec '12 - 13:58 
GeneralMy vote of 5 Pinmemberask.sagaram3 Oct '12 - 8:38 
i appreciate the work and it helped me in my job
Questionvb.net vesion Pinmemberjeleostephen2 Oct '12 - 1:09 
hello sir, do you have a vb.net version for this, i don't know how to convert it and i dont much understand c#, please help me. thank you
AnswerRe: vb.net vesion PinmemberRanjan.D4 Oct '12 - 2:57 
Questiongsm module Pinmembertrixie tiglao29 Sep '12 - 22:13 
what is the name or brand of the gsm module you used and the programming language???
AnswerRe: gsm module PinmemberRanjan.D4 Oct '12 - 2:57 
Questioncheck port is used or not Pinmemberdanar_kalari24 Sep '12 - 2:28 
Thank you for great work I want to check if the com port is used at this time or not because I want to use it in side asp.net so if I send request from a browser while other browser is using the com port i get
A first chance exception of type 'GsmComm.GsmCommunication.CommException' occurred in GSMCommunication.dll
 
Thank you
AnswerRe: check port is used or not PinmemberRanjan.D9 Oct '12 - 19:16 
Questionnot able to send sms Pinmemberomprakash.engg20 Sep '12 - 9:29 
sir,
i am geting error " PHONE REPORTING GENERIC COMMUNICATION ERROR OR SYNTEX ERROR"
can u add auto reply option in this application
omprakash.engg@gmail.com
9820160423

QuestionNo data received from phone. Pinmemberjyotsnasukle11 Sep '12 - 1:09 
Sir,
on send data, it throw exception that 'No data received from phone.'
GeneralThanks PinmemberPuran Maury31 Aug '12 - 2:30 
Sir that code is very usefull for me.
QuestionUSB modem not recognized Pinmembersudguru26 Aug '12 - 18:40 
Hi I am using USB Modem but I am getting "No phone connected" Message. Will this code connect with USB modem? please help.
AnswerRe: USB modem not recognized Pinmembersotsprodigy28 Aug '12 - 9:50 
GeneralRe: USB modem not recognized PinmemberGlendonz18 Dec '12 - 14:12 

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.130516.1 | Last Updated 10 Sep 2007
Article Copyright 2007 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid