Integrating C# With Embedded System
Integrating C# With Embedded System
Table of Contents
OVERVIEW..................................................................................................................................................... 4
Getting started .............................................................................................................................................. 4
CREATING NEW PROJECT .............................................................................................................................. 4
TOOLBOX....................................................................................................................................................... 6
PROPERTIES WINDOW .................................................................................................................................. 8
BUILD AND DEBUGGING TOOL ..................................................................................................................... 9
BUILD MENU: ............................................................................................................................................ 9
DEBUG MENU: ........................................................................................................................................ 10
WINDOWS PROGRAMMING ....................................................................................................................... 10
HELLO WORLD......................................................................................................................................... 10
DATA TYPES AND VERIABLES ...................................................................................................................... 12
BOOLEAN TYPES ...................................................................................................................................... 12
Numeric types: Integrals, Floating Point, Decimal .................................................................................. 13
String type ................................................................................................................................................... 13
Arrays ...................................................................................................................................................... 13
CONTROL FLOW .......................................................................................................................................... 14
The if Statement ..................................................................................................................................... 14
The switch Statement ............................................................................................................................. 15
LOOPS.......................................................................................................................................................... 16
The while Loop ........................................................................................................................................ 16
The do Loop ............................................................................................................................................ 17
The for Loop ................................................................................................................................................ 17
OUTPUT:...................................................................................................................................................... 18
The foreach Loop .................................................................................................................................... 18
SERIAL COMMUNICATION .......................................................................................................................... 19
Setting Up................................................................................................................................................ 19
OUTPUT:...................................................................................................................................................... 24
USB RFID INTERFACE WITH C# .................................................................................................................... 25
www.reserachdesignlab.com Page 2
C# Tutorial
www.reserachdesignlab.com Page 3
C# Tutorial
OVERVIEW
C# is designed for Common Language Infrastructure (CLI), which consists of the executable code
and runtime environment that allows use of various high-level languages to be used on different
computer platforms and architectures.
The following reasons make C# a widely used professional language:
Getting started
Once Visual Studio is running the first step is to create a new project. Do this by selecting New
Project from the File menu. This will cause the New Project window to appear containing a range of
different types of project. For the purposes of this tutorial we will be developing a Windows Forms
Application so make sure that this option is selected.
www.reserachdesignlab.com Page 4
C# Tutorial
In this window you will select an appropriate template based on what kind of application you want to
create, and a name and location for your project and solution.
Console application.
WPF application
Silverlight application.
www.reserachdesignlab.com Page 5
C# Tutorial
TOOLBOX
When you select WINDOWS FORM APPLICATION, you will get FORM DESIGN WINDOW,it is used
to design USER interface by making use of TOOLBOX on the left side of window,
The TOOLBOX contains all the necessary controls, etc. You need to create a user interface by
making use of these controls as shown in figure below.
www.reserachdesignlab.com Page 6
C# Tutorial
In order to use these controls, just drag and drop it on to your Design forms, as shown in figure.
The following screenshot shows, making use of these toolbox controls for designing the user interface
on DESIGN FORM.
www.reserachdesignlab.com Page 7
C# Tutorial
PROPERTIES WINDOW
Each TOOLBOX we have used on our form has many properties that we can set. This is done by using
Properties window. We can find the property window on the right bottom side of your project
www.reserachdesignlab.com Page 8
C# Tutorial
BUILD MENU:
Below we see the Build menu. The most used Build tool is BUILD SOLUTIONS.
www.reserachdesignlab.com Page 9
C# Tutorial
DEBUG MENU:
In order to RUN or DEBUG your windows form we make use of DEBUG TOOLs. The most used
debug tool is START DEBUGGING.it can be find the shortcut for this on the top of your visual studio
windows.
WINDOWS PROGRAMMING
When creating ordinary windows form application, we can select between the following:
HELLO WORLD
We start by creating traditional “HELLO WORLD” application using Windows Form Application is
shown below. The visual studio UI shown below.
www.reserachdesignlab.com Page 10
C# Tutorial
In this application we make use of simple textbox and Button(Button name is changed to Submit in the
properties) when we click on submit the “HELLO WORLD ”massage will be displayed in the Textbox.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
www.reserachdesignlab.com Page 11
C# Tutorial
using System.Windows.Forms;
namespace WindowsFormsApplication9
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Boolean type
Numeric types: Integrals, Floating Point, Decimal
String type
BOOLEAN TYPES
Boolean types are declared using the keyword “bool”. They have two values: “true” or
“false”. In other languages, such as C and C++, boolean conditions can be satisfied where 0
means false and anything else means true. However, in C# the only values that satisfy a
boolean condition is true and false, which are official keywords.
Example:
www.reserachdesignlab.com Page 12
C# Tutorial
noContent=false
Example:
int i=35;
long y=654654;
float x;
double y;
decimal z;
String type
Example:
Arrays
Example:
www.reserachdesignlab.com Page 13
C# Tutorial
CONTROL FLOW
The if Statement
The switch Statement
The if Statement
The if statement is probably the most used mechanism to control the flow in
your application. An if statement allows you to take different paths of logic,
depending on a given condition. When the condition evaluates to a Boolean true, a
block of code for that true condition will execute. You have the option of a single if
statement, multiple else if statements, and an optional else statement.
Example:
myTest=false;
if (myTest==false)
MessageBox.Show("Hello”);
}
output:
www.reserachdesignlab.com Page 14
C# Tutorial
Example:
bool myTest;
myTest=true;
if (myTest == false)
{
MessageBox.Show("Hello1");
}
else
{
MessageBox.Show("Hello2");
Example:
int myTest;
myTest=2;
if (myTest == 1)
{
MessageBox.Show("Hello1");
}
else if (myTest == 2)
{
MessageBox.Show("Hello2");
}
else
{
MessageBox.Show("Hello3");
}
Another form of selection statement is the switch statement, which executes a set of
logic depending on the value of a given parameter. The types of the values a switch
statement operates on can be booleans, enums, integral types, and strings.
Example:
www.reserachdesignlab.com Page 15
C# Tutorial
switch (myTest)
{
case 1:
MessageBox.Show("Hello1
"); break;
case 2:
MessageBox.Show("Hello2
"); break;
default:
MessageBox.Show("Hello”
); break;
}
LOOPS
A while loop will check a condition and then continues to execute a block of code as long as
the condition evaluates to a boolean value of true.
Example:
int myInt = 0;
while (myInt < 10)
{
MessageBox.Show("Inside Loop: " +
myInt.ToString()); myInt++;
}
MessageBox.Show("Outside Loop: " + myInt.ToString());
www.reserachdesignlab.com Page 16
C# Tutorial
OUTPUT:
The do Loop
A do loop is similar to the while loop, except that it checks its condition at the end of
the loop. This means that the do loop is guaranteed to execute at least one time. On the
other hand, a while loop evaluates its boolean expression at the beginning and there is
generally no guarantee that the statements inside the loop will be executed, unless you
program the code to explicitly do so.
Example:
int myInt = 0;
do
myInt++;
A for loop works like a while loop, except that the syntax of the for loop includes
initialization and condition modification. for loops are appropriate when you know exactly
how many times you want to perform the statements within the loop.
Example:
www.reserachdesignlab.com Page 17
C# Tutorial
OUTPUT:
A foreach loop is used to iterate through the items in a list. It operates on arrays or
collections.
Example:
www.reserachdesignlab.com Page 18
C# Tutorial
SERIAL COMMUNICATION
Setting Up
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
System.IO.Ports is the class to use without resulting to low level hacking. This covers all the
serial ports that appear on the machine.
This will create an object called ComPort. This will create a serial port object with the following
parameters as default 9600bps, no parity, one stop bit and no flow control.
www.reserachdesignlab.com Page 19
C# Tutorial
This is standard Windows Forms Application via File menu. To this add the button
(name Ports) and a Rich Text Box.The button is called btnGetSerialPorts and the Rich Text called
as rtbIncomingData (the name will become apparent later).The rich text box is used as it is
more flexible than the ordinary text box. Its uses for sorting and aligning text are considerably
more than the straight textbox.
This shows all the devices that appear as com ports, a mistake to make is thinking that a
device if plugged into the USB will appear as a COM Port.
The baud rate is the amount of possible events that can happen in a second. It is
displays usually as a number of bit per second, the possible number that can be used are 300,
600, 1200, 2400, 9600, 14400, 19200, 38400, 57600, and 115200 (these come from the UAR
8250 chip is used, if a 16650 the additional rates of 230400, 460800 and 921600) .
The next box is the number of Data bits, these represent the total number of transitions
of the data transmission (or Tx line) 8 is the standard ( 8 is useful for reading certain embedded
application as it gives two nibbles (4 bit sequences).
The Handshaking property is used when a full set of connections are used (such as the grey 9
way D-types that litter my desk). It was used originally to ensure both ends lined up with each other and
the data was sent and received properly. A common handshake was required between both sender and
receiver. Below is the code for the combo box:
www.reserachdesignlab.com Page 20
C# Tutorial
Here is the complete code for serial communication between transmitter and receiver.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO.Ports;
using System.Windows.Forms;
namespace CodeProjectSerialComms
{
public partial class Form1 : Form
{
SerialPort ComPort = new SerialPort();
public Form1()
{
InitializeComponent();
SerialPinChangedEventHandler1 = new SerialPinChangedEventHandler(PinChanged);
ComPort.DataReceived += new
System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
}
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
www.reserachdesignlab.com Page 21
C# Tutorial
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
//get first item print in text
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(300);
cboBaudRate.Items.Add(600);
cboBaudRate.Items.Add(1200);
cboBaudRate.Items.Add(2400);
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(14400);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(7);
cboDataBits.Items.Add(8);
//get the first item print it in the text
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
//get the first item print in the text
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
//get the first item print in the text
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
//get the first item print it in the text
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
www.reserachdesignlab.com Page 22
C# Tutorial
if (btnPortState.Text == "Closed")
{
btnPortState.Text = "Open";
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits),
cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake),
cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.Open();
}
else if (btnPortState.Text == "Open")
{
btnPortState.Text = "Closed";
ComPort.Close();
}
}
private void rtbOutgoing_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)13) // enter key
{
ComPort.Write("\r\n");
rtbOutgoing.Text = "";
}
else if (e.KeyChar < 32 || e.KeyChar > 126)
{
e.Handled = true; // ignores anything else outside printable ASCII range
}
else
{
ComPort.Write(e.KeyChar.ToString());
www.reserachdesignlab.com Page 23
C# Tutorial
}
}
private void btnHello_Click(object sender, EventArgs e)
{
ComPort.Write("Hello World!");
}
}
OUTPUT:
www.reserachdesignlab.com Page 24
C# Tutorial
Normally the System.Net Contains the Serial Port Class and also available in the Toolbox as Serial
port component for your Win Forms App
The following code is for reading RFID data from serial port.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
www.reserachdesignlab.com Page 25
C# Tutorial
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace com
{
public partial class Form1 : Form
{
CommManager com = new CommManager();
string RxString;
public Form1()
{
InitializeComponent();
private void Form1_Load_1(object sender, EventArgs e) //when form loads setting a values.
{
com .SetPortNameValues(comboBox2 );
com.Parity="None";
com.BaudRate = "9600";
com.StopBits="One";
com.DataBits = "8";
com.DisplayWindow=richTextBox1;
www.reserachdesignlab.com Page 26
C# Tutorial
Here we made use of combobox,richtextbox for displaying RFID DATA after reading and OPEN button to
open the selected comport.for above project you have to create a class for comport management, the
code for this class as given below and it is common for all the serial communication interface.
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.Drawing;
using System.IO.Ports;
using System.Windows.Forms;
public class CommManager
{
www.reserachdesignlab.com Page 27
C# Tutorial
Hex,
Bin
}
/// <summary>
/// enumeration to hold our message types
/// </summary>
public enum MessageType
{
Incoming,
Outgoing,
Normal,
Warning,
Error
}
#endregion
www.reserachdesignlab.com Page 28
C# Tutorial
/// <summary>
/// property to hold the Parity
/// of our manager class
/// </summary>
public string Parity
{
get { return _parity; }
set { _parity = value; }
}
/// <summary>
/// property to hold the StopBits
/// of our manager class
/// </summary>
public string StopBits
{
get { return _stopBits; }
set { _stopBits = value; }
}
/// <summary>
/// property to hold the DataBits
/// of our manager class
/// </summary>
public string DataBits
{
get { return _dataBits; }
set { _dataBits = value; }
}
/// <summary>
/// property to hold the PortName
/// of our manager class
/// </summary>
public string PortName
{
get { return _portName; }
set { _portName = value; }
}
/// <summary>
/// property to hold our TransmissionType
/// of our manager class
/// </summary>
public TransmissionType CurrentTransmissionType
{
get { return _transType; }
set { _transType = value; }
}
www.reserachdesignlab.com Page 29
C# Tutorial
/// <summary>
/// property to hold our display window
/// value
/// </summary>
public RichTextBox DisplayWindow
{
get { return _displayWindow; }
set { _displayWindow = value; }
}
www.reserachdesignlab.com Page 30
C# Tutorial
/// <summary>
/// Comstructor to set the properties of our
/// serial port communicator to nothing
/// </summary>
public CommManager()
{
_baudRate = string.Empty;
_parity = string.Empty;
_stopBits = string.Empty;
_dataBits = string.Empty;
_portName = "COM1";
_displayWindow = null;
//add event handler
comPort.DataReceived += comPort_DataReceived;
}
public CommManager(ref ProgressBar strngthBar)
{
_baudRate = string.Empty;
_parity = string.Empty;
_stopBits = string.Empty;
_dataBits = string.Empty;
_portName = "COM1";
_displayWindow = null;
//add event handler
comPort.DataReceived += comPort_DataReceived;
}
#endregion
#region "WriteData"
www.reserachdesignlab.com Page 31
C# Tutorial
try
{
switch (CurrentTransmissionType)
{
case TransmissionType.Text:
//first make sure the port is open
//if its not open then open it
if (!(comPort.IsOpen == true))
{
comPort.Open();
}
//send the message to the port
comPort.Write(msg);
break;
case TransmissionType.Hex:
try
{
//convert the message to byte array
byte[] newMsg = HexToByte(msg);
if (!write)
{
DisplayData(_type, _msg);
return;
}
//send the message to the port
comPort.Write(newMsg, 0, newMsg.Length);
//convert back to hex and display
_type = MessageType.Outgoing;
// + "" + Environment.NewLine + ""
_msg = ByteToHex(newMsg);
DisplayData(_type, _msg);
}
catch (FormatException ex)
{
//display error message
_type = MessageType.Error;
_msg = ex.Message + "" + Environment.NewLine + "";
DisplayData(_type, _msg);
}
finally
{
www.reserachdesignlab.com Page 32
C# Tutorial
_displayWindow.SelectAll();
}
break;
default:
//first make sure the port is open
//if its not open then open it
if (!(comPort.IsOpen == true))
{
comPort.Open();
}
//send the message to the port
comPort.Write(msg);
break;
}
}
catch (Exception ex)
{
}
}
#endregion
#region "HexToByte"
/// <summary>
/// method to convert hex string into a byte array
/// </summary>
/// <param name="msg">string to convert</param>
/// <returns>a byte array</returns>
private byte[] HexToByte(string msg)
{
if (msg.Length % 2 == 0)
{
//remove any spaces from the string
_msg = msg;
_msg = msg.Replace(" ", "");
//create a byte array the length of the
//divided by 2 (Hex is 2 characters in length)
byte[] comBuffer = new byte[_msg.Length / 2];
for (int i = 0; i <= _msg.Length - 1; i += 2)
{
www.reserachdesignlab.com Page 33
C# Tutorial
#region "ByteToHex"
/// <summary>
/// method to convert a byte array into a hex string
/// </summary>
/// <param name="comByte">byte array to convert</param>
/// <returns>a hex string</returns>
private string ByteToHex(byte[] comByte)
{
//create a new StringBuilder object
StringBuilder builder = new StringBuilder(comByte.Length * 3);
//loop through each byte in the array
foreach (byte data in comByte)
{
builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
//convert the byte to a string and add to the stringbuilder
}
//return the converted value
return builder.ToString().ToUpper();
}
#endregion
#region "DisplayData"
/// <summary>
/// Method to display the data to and
/// from the port on the screen
/// </summary>
/// <remarks></remarks>
[STAThread()]
private void DisplayData(MessageType type, string msg)
{
_displayWindow.Invoke(new EventHandler(DoDisplay));
}
www.reserachdesignlab.com Page 34
C# Tutorial
#endregion
#region "OpenPort"
public bool OpenPort()
{
try
{
//first check if the port is already open
//if its open then close it
if (comPort.IsOpen == true)
{
comPort.Close();
}
www.reserachdesignlab.com Page 35
C# Tutorial
}
}
#endregion
#region "SetParityValues"
public void SetParityValues(object obj)
{
foreach (string str in Enum.GetNames(typeof(Parity)))
{
((ComboBox)obj).Items.Add(str);
}
}
#endregion
#region "SetStopBitValues"
public void SetStopBitValues(object obj)
{
foreach (string str in Enum.GetNames(typeof(StopBits)))
{
((ComboBox)obj).Items.Add(str);
}
}
#endregion
#region "SetPortNameValues"
#region "comPort_DataReceived"
/// <summary>
/// method that will be called when theres data waiting in the buffer
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//determine the mode the user selected (binary/string)
switch (CurrentTransmissionType)
{
case TransmissionType.Text:
//user chose string
//read data waiting in the buffer
string msg = comPort.ReadExisting();
//MessageBox.Show(msg)
www.reserachdesignlab.com Page 36
C# Tutorial
try
{
}
catch (Exception ex)
{
}
break;
case TransmissionType.Hex:
//user chose binary
//retrieve number of bytes in the buffer
int bytes = comPort.BytesToRead;
//create a byte array to hold the awaiting data
byte[] comBuffer = new byte[bytes];
//read the data and store it
comPort.Read(comBuffer, 0, bytes);
//display the data to the user
_type = MessageType.Incoming;
_msg = ByteToHex(comBuffer) + "" + Environment.NewLine + "";
DisplayData(MessageType.Incoming, ByteToHex(comBuffer) + "" +
Environment.NewLine + "");
break; // TODO: might not be correct. Was : Exit Select
break;
default:
//read data waiting in the buffer
string str = comPort.ReadExisting();
try
{
}
catch (Exception ex)
{
}
break;
}
www.reserachdesignlab.com Page 37
C# Tutorial
}
#endregion
#region "DoDisplay"
private void DoDisplay(object sender, EventArgs e)
{
_displayWindow.SelectedText = string.Empty;
_displayWindow.SelectionFont = new Font(_displayWindow.SelectionFont,
FontStyle.Bold);
_displayWindow.SelectionColor = MessageColor[Convert.ToInt32(_type)];
_displayWindow.AppendText(_msg);
_displayWindow.ScrollToCaret();
}
#endregion
if (pos >= 0)
{
return value.Remove(pos, rmv.Length);
}
return value;
}
Output:
www.reserachdesignlab.com Page 38
C# Tutorial
Here we are making use of 4 channel relay to controlling it, The following picture show the
design part of it, in this we have used one combo box for reading com port and open button to open the
selected port, and DATA text box, this is for entering manually which relay should turn on suppose if you
enter ‘ff’ it will turn on relay1.
www.reserachdesignlab.com Page 39
C# Tutorial
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace ft245rlAPP
{
public partial class Form1 : Form
{
CommManager comMangr=new CommManager();
public Form1()
{
InitializeComponent();
}
comMangr.BaudRate = "9600";
comMangr.DataBits = "8";
comMangr.Parity = "None";
//comMangr.DisplayWindow = terminalRichTextBox1
comPortCmb.SelectedIndex = 0;
comMangr.PortName =
comPortCmb.Items[comPortCmb.SelectedIndex].ToString();
comMangr.StopBits = "One";
//comMangr.SignalStrengthBar = SigStrProgressBar1
www.reserachdesignlab.com Page 40
C# Tutorial
// comMangr.SignalStrengthLbl = signaStrDb
comMangr.CurrentTransmissionType = CommManager.TransmissionType.Hex;
System.Diagnostics.Process.Start("C:\\\\ft245RL_Init.exe");
System.Threading.Thread.Sleep(5000);
}
Button2.Enabled = false;
Button3.Enabled = false;
Button4.Enabled = false;
Button5.Enabled = false;
Button6.Enabled = false;
Button7.Enabled = false;
Button8.Enabled = false;
Button9.Enabled = false;
Button10.Enabled = false;
www.reserachdesignlab.com Page 41
C# Tutorial
{
comMangr.WriteData(TextBox1.Text);
}
}
}
And create same commanger class as we discussed in RFID DATA READ FROM SERIAL PORT
SECTION.
www.reserachdesignlab.com Page 42
C# Tutorial
GSM INERFACE
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.
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.
www.reserachdesignlab.com Page 43
C# Tutorial
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
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.
The FORM DESIGN as show below, Here we using combo box for port selection and textbox for entering
mobile number to send sms,and message field to type message and send button.
www.reserachdesignlab.com Page 44
C# Tutorial
The complete code as given below, Here we have to create two class 1)sms ,2)program
The class sms will set all pre-requirements in order to send sms,and port values and program class will
load the forms and this will initiate the application.
Form1.cs:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
namespace SendSMS
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
loadPorts();
}
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
www.reserachdesignlab.com Page 45
C# Tutorial
namespace SendSMS
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
Sms.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.Windows.Forms;
namespace SendSMS
{
class SMS
{
SerialPort serialPort;
public SMS(string comPort)
{
this.serialPort = new SerialPort();
this.serialPort.PortName = comPort;
this.serialPort.BaudRate = 9600;
this.serialPort.Parity = Parity.None;
this.serialPort.DataBits = 8;
this.serialPort.StopBits = StopBits.One;
this.serialPort.Handshake = Handshake.RequestToSend;
this.serialPort.DtrEnable = true;
this.serialPort.RtsEnable = true;
this.serialPort.NewLine = System.Environment.NewLine;
}
public bool sendSMS(string cellNo, string sms)
{
string messages = null;
messages = sms;
www.reserachdesignlab.com Page 46
C# Tutorial
if (this.serialPort.IsOpen == true)
{
try
{
this.serialPort.WriteLine("AT" + (char)(13));
Thread.Sleep(4);
this.serialPort.WriteLine("AT+CMGF=1" + (char)(13));
Thread.Sleep(5);
this.serialPort.WriteLine("AT+CMGS=\"" + cellNo + "\"");
Thread.Sleep(10);
this.serialPort.WriteLine(">" + messages + (char)(26));
}
catch (Exception ex)
{
MessageBox.Show(ex.Source);
}
return true;
}
else
return false;
}
www.reserachdesignlab.com Page 47