Thursday, February 5, 2009

Serial ports in c#

If you are using Serial (COM) port for communication with devices, then most usually your application will have to list all the available COM ports available unless you know the particular port name. The Following code will list all the available COM ports in your Computer.

First add the using System.IO.Ports; namespace. The following code add all the available serial ports into a combobox:

foreach (string portname in SerialPort.GetPortNames())
{
cmbport.Items.Add(portname);
}

the GetPortNames() will return all the serial port names.

Now To communicate with the Device you can use the write and read commandds of Serial port. Following is an example code that sends an AT command to a GSM modem:


SerialPort port;
string str;
port = new SerialPort(cmbport.Text, 19200, Parity.None, 8, StopBits.One);
port.Handshake = Handshake.RequestToSend;
port.NewLine = System.Environment.NewLine;
port.ReadTimeout = 60000;
port.WriteTimeout = 5000;
port.Open();
try
{
if (port.IsOpen)
{
port.WriteLine("AT\r");
str = port.ReadExisting(); //Response text from GSM modem
Messagebox.show(str);
}
}
catch (Exception ex)
{
MessageBox.Show("Try another Port. Phone not detected","CONNECTION ERROR",MessageBoxButtons.OK,MessageBoxIcon.Error);
port.Close();
}


cochin cellphone software developers

4 comments:

  1. port.WriteLine("AT\r");

    -->> Thread.Sleep(1000); <<--

    str = port.ReadExisting();

    ReplyDelete
  2. These are port numbers. How do I get the name? That is if I look at device manager, COM17 is listed as "USB Serial Port (COM17)". When I do the above, all I get is "COM17". I need to know that this is the USB port. How do I do that?

    ReplyDelete
  3. Add Reference to System.Management and use following code

    using System.Management;


    ManagementObjectSearcher searcher = new ManagementObjectSearcher("Select * from WIN32_SerialPort");
    foreach (ManagementObject Port in searcher.Get())
    {
    string a = string)Port.GetPropertyValue("Name");
    MessageBox.Show(a);
    }

    ReplyDelete
  4. Hi
    I need to write a program which has to check whther any application is using the COM1 port and print port available or port not available.
    any help much appreciated
    ANi

    ReplyDelete

LinkWithin

Related Posts with Thumbnails