ethiraj
ethiraj

Reputation: 67

How to Send & Receive data in Serial-port in win-forms C#

I have been working on a card-reader application in Win-Forms C#. Below is my sample code. It only reads once and shows the messagebox, after that it doesn't show again. DataReceived event is not triggering a 2nd time. I tested it in hyper-terminal and it works properly.

C# sample Code:-

SerialPort port = new SerialPort("COM3", 115200, Parity.Even, 8, StopBits.One);
try
{
    if (port.IsOpen == true)
        port.Close();

    if (!port.IsOpen)
    {
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
        port.Open();
        port.WriteLine("RI \n");
        port.WriteLine("R100002 \n");
        port.WriteTimeout = 300;
    }

    port.Close();
}
catch (Exception ex)
{
    port.Close();
    MessageBox.Show(ex.Message);
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   SerialPort sp = (SerialPort)sender;
   MessageBox.Show(sp.ReadExisting());
} 

Does anybody having working sample code? Pls share any ideas to correct the issue.

Upvotes: 1

Views: 2334

Answers (2)

ethiraj
ethiraj

Reputation: 67

here is my successful Tested code for card reader:-

I find out this combination from hyper-terminal, just try :)-

                port.PortName = txt_Token_port_Name.Text;
                port.BaudRate = Convert.ToInt32(txt_Token_Bud_rate.Text);
                port.Parity = Parity.None;
                port.DataBits = 8;
                port.StopBits = StopBits.One;

                if (port.IsOpen == true)
                    port.Close();

                if (port.IsOpen == false)
                {
                    port.Open();
                    port.ReadTimeout = 3000;
                    port.Write("t\r");
                    port.Write("R1");
                    port.Write("00002");
                    txt_Token_TokenNo.Text = port.ReadLine();

                    port.Close();
                }

Upvotes: 0

Ben Voigt
Ben Voigt

Reputation: 283614

You are closing the port immediately after writing. A closed port won't receive incoming data.

Don't close the port until you are done with it.

Upvotes: 1

Related Questions