5 Replies - 37258 Views - Last Post: 09 May 2009 - 12:14 AM Rate Topic: -----

#1 sahu.shikha  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 7
  • Joined: 24-March 09

How To Read Data From Serial Port

Posted 09 April 2009 - 11:43 PM

Hi

I Am C# Programmer new in Serial Port programming.... Sending is working when i Checked to Hyperterminal..i am Able to See what Data i Am sending Through the Application...When At Time OF receiving Data From The Port is not Working.. it means I am Unable To Reterive Data From port what Data i am Sending...plzzzzzzzzz i am struck from last so many days... i am not getting the solution... i Searched a lot and also download some Sample.. in case of sending they worked but still problem is receiving..... :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: plzzzzzzzzzzzzzz
I am Pasting My Some Code

namespace SerialPort
{
    public partial class ReadSample3 : Form
    {
        string InputData = String.Empty;
        System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        delegate void SetTextCallback(string text);
        public ReadSample3()
        {
            InitializeComponent();
            //string[] ports = System.IO.Ports.SerialPort.GetPortNames();

            // Add all port names to the combo box:
            //foreach (string port in ports)
            //{
            //    //cmbComSelect.Items.Add(port);
            //    comboBox1.Items.Add(port);
            //}
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
          
        }
        private void ReadSample3_Load(object sender, EventArgs e)
        {
            if (port.IsOpen)
                port.PortName = "COM1";
            //stsStatus.Text = port.PortName + ": 9600,8N1";

            // try to open the selected port:
            try
            {
               port.PortName = "COM1";

                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.DtrEnable = true;
                port.Handshake = Handshake.None;
                port.DtrEnable = true;
                port.Open();
                //If i set port.Handshake= Handshake.RequestToSend and requestToSend= True so Data IS Not Showing In The Hyper Terminal MAY BE DATA IS NOT RECEIVING/////////
                //port.BaudRate = 9600;
                //port.DataBits=
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName +
                "cannot be opened!", "RS232 tester",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //comboBox1.SelectedText = "";
                // stsStatus.Text = "Select serial port!";
            }
        }
        //private void comboBox1_SelectionchangeCommitted(object sender, EventArgs e)
        //{
        //    //if (port.IsOpen)
        //    //    port.PortName = "COM1";
        //    ////stsStatus.Text = port.PortName + ": 9600,8N1";

        //    //// try to open the selected port:
        //    //try
        //    //{
        //    //    port.Open();
               
        //    //}
        //    //// give a message, if the port is not available:
        //    //catch
        //    //{
        //    //    MessageBox.Show("Serial port " + port.PortName +
        //    //    "cannot be opened!", "RS232 tester",
        //    //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    //    comboBox1.SelectedText = "";
        //    //   // stsStatus.Text = "Select serial port!";
        //    //}
        //    ////port.Close();
        //}
        private void button2_Click(object sender, EventArgs e)
        {
            //port.Open();
            if (port.IsOpen) port.WriteLine(textBox2.Text);
            else MessageBox.Show("Serial port is closed!",
                                 "RS232 tester",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            textBox2.Clear();
            //port.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }
        private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
        {
            InputData = port.ReadExisting();
            //byte[] receiveBuffer = new byte[128];
            //int bufferIndex = 0;
            //int bytesRead = 0;
            //int startPacketIndex = 0;
            //int expectedPacketLength = -1;
            //bool expectedPacketLengthIsSet = false;
            //int numBytesToRead = receiveBuffer.Length; 
            //bytesRead += port.Read(receiveBuffer, bufferIndex, numBytesToRead);
            if (InputData != String.Empty)
            {
                // txtIn.Text = InputData;
                // because of different threads this
                // does not work properly !!
                SetText(InputData);
            }
        }
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
                else this.textBox1.Text += text;
        }
    }
}





plzzzzzzzzz help me ... i am in problem...

*** MOD EDIT: Fixed horrific code tags ***

This post has been edited by JackOfAllTrades: 10 April 2009 - 04:45 AM


Is This A Good Question/Topic? 0
  • +

Replies To: How To Read Data From Serial Port

#2 fishberg5051  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 1
  • Joined: 10-April 09

Re: How To Read Data From Serial Port

Posted 10 April 2009 - 08:56 AM

View Postsahu.shikha, on 9 Apr, 2009 - 10:43 PM, said:

Hi

I Am C# Programmer new in Serial Port programming.... Sending is working when i Checked to Hyperterminal..i am Able to See what Data i Am sending Through the Application...When At Time OF receiving Data From The Port is not Working.. it means I am Unable To Reterive Data From port what Data i am Sending...plzzzzzzzzz i am struck from last so many days... i am not getting the solution... i Searched a lot and also download some Sample.. in case of sending they worked but still problem is receiving..... :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: plzzzzzzzzzzzzzz
I am Pasting My Some Code

namespace SerialPort
{
    public partial class ReadSample3 : Form
    {
        string InputData = String.Empty;
        System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        delegate void SetTextCallback(string text);
        public ReadSample3()
        {
            InitializeComponent();
            //string[] ports = System.IO.Ports.SerialPort.GetPortNames();

            // Add all port names to the combo box:
            //foreach (string port in ports)
            //{
            //    //cmbComSelect.Items.Add(port);
            //    comboBox1.Items.Add(port);
            //}
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
          
        }
        private void ReadSample3_Load(object sender, EventArgs e)
        {
            if (port.IsOpen)
                port.PortName = "COM1";
            //stsStatus.Text = port.PortName + ": 9600,8N1";

            // try to open the selected port:
            try
            {
               port.PortName = "COM1";

                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.DtrEnable = true;
                port.Handshake = Handshake.None;
                port.DtrEnable = true;
                port.Open();
                //If i set port.Handshake= Handshake.RequestToSend and requestToSend= True so Data IS Not Showing In The Hyper Terminal MAY BE DATA IS NOT RECEIVING/////////
                //port.BaudRate = 9600;
                //port.DataBits=
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName +
                "cannot be opened!", "RS232 tester",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //comboBox1.SelectedText = "";
                // stsStatus.Text = "Select serial port!";
            }
        }
        //private void comboBox1_SelectionchangeCommitted(object sender, EventArgs e)
        //{
        //    //if (port.IsOpen)
        //    //    port.PortName = "COM1";
        //    ////stsStatus.Text = port.PortName + ": 9600,8N1";

        //    //// try to open the selected port:
        //    //try
        //    //{
        //    //    port.Open();
               
        //    //}
        //    //// give a message, if the port is not available:
        //    //catch
        //    //{
        //    //    MessageBox.Show("Serial port " + port.PortName +
        //    //    "cannot be opened!", "RS232 tester",
        //    //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    //    comboBox1.SelectedText = "";
        //    //   // stsStatus.Text = "Select serial port!";
        //    //}
        //    ////port.Close();
        //}
        private void button2_Click(object sender, EventArgs e)
        {
            //port.Open();
            if (port.IsOpen) port.WriteLine(textBox2.Text);
            else MessageBox.Show("Serial port is closed!",
                                 "RS232 tester",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            textBox2.Clear();
            //port.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }
        private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
        {
            InputData = port.ReadExisting();
            //byte[] receiveBuffer = new byte[128];
            //int bufferIndex = 0;
            //int bytesRead = 0;
            //int startPacketIndex = 0;
            //int expectedPacketLength = -1;
            //bool expectedPacketLengthIsSet = false;
            //int numBytesToRead = receiveBuffer.Length; 
            //bytesRead += port.Read(receiveBuffer, bufferIndex, numBytesToRead);
            if (InputData != String.Empty)
            {
                // txtIn.Text = InputData;
                // because of different threads this
                // does not work properly !!
                SetText(InputData);
            }
        }
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
                else this.textBox1.Text += text;
        }
    }
}





plzzzzzzzzz help me ... i am in problem...

*** MOD EDIT: Fixed horrific code tags ***

Was This Post Helpful? 0
  • +
  • -

#3 n8wxs  Icon User is offline

  • --... ...-- -.. . -. ---.. .-- -..- ...
  • member icon

Reputation: 972
  • View blog
  • Posts: 3,878
  • Joined: 07-January 08

Re: How To Read Data From Serial Port

Posted 10 April 2009 - 09:06 PM

View Postsahu.shikha, on 9 Apr, 2009 - 10:43 PM, said:

...
plzzzzzzzzz help me ... i am in problem...

*** MOD EDIT: Fixed horrific code tags ***


See PsychoCoder's Serial Port Communication in C# tutorial
Was This Post Helpful? 0
  • +
  • -

#4 prabhakara85  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-May 09

Re: How To Read Data From Serial Port

Posted 08 May 2009 - 05:01 AM

Dear Sir,

i am using RS232 to read data from weighing machine using asp.net(C#), sometimes i am getting weight from the weighing machine and that is displaying in the textbox.. eventhough i am using begininvoke sometimes data will not be display in the textbox.. Please Help me..

Thanks


View Postfishberg5051, on 10 Apr, 2009 - 07:56 AM, said:

View Postsahu.shikha, on 9 Apr, 2009 - 10:43 PM, said:

Hi

I Am C# Programmer new in Serial Port programming.... Sending is working when i Checked to Hyperterminal..i am Able to See what Data i Am sending Through the Application...When At Time OF receiving Data From The Port is not Working.. it means I am Unable To Reterive Data From port what Data i am Sending...plzzzzzzzzz i am struck from last so many days... i am not getting the solution... i Searched a lot and also download some Sample.. in case of sending they worked but still problem is receiving..... :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: :?: plzzzzzzzzzzzzzz
I am Pasting My Some Code

namespace SerialPort
{
    public partial class ReadSample3 : Form
    {
        string InputData = String.Empty;
        System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        delegate void SetTextCallback(string text);
        public ReadSample3()
        {
            InitializeComponent();
            //string[] ports = System.IO.Ports.SerialPort.GetPortNames();

            // Add all port names to the combo box:
            //foreach (string port in ports)
            //{
            //    //cmbComSelect.Items.Add(port);
            //    comboBox1.Items.Add(port);
            //}
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
          
        }
        private void ReadSample3_Load(object sender, EventArgs e)
        {
            if (port.IsOpen)
                port.PortName = "COM1";
            //stsStatus.Text = port.PortName + ": 9600,8N1";

            // try to open the selected port:
            try
            {
               port.PortName = "COM1";

                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.DtrEnable = true;
                port.Handshake = Handshake.None;
                port.DtrEnable = true;
                port.Open();
                //If i set port.Handshake= Handshake.RequestToSend and requestToSend= True so Data IS Not Showing In The Hyper Terminal MAY BE DATA IS NOT RECEIVING/////////
                //port.BaudRate = 9600;
                //port.DataBits=
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName +
                "cannot be opened!", "RS232 tester",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                //comboBox1.SelectedText = "";
                // stsStatus.Text = "Select serial port!";
            }
        }
        //private void comboBox1_SelectionchangeCommitted(object sender, EventArgs e)
        //{
        //    //if (port.IsOpen)
        //    //    port.PortName = "COM1";
        //    ////stsStatus.Text = port.PortName + ": 9600,8N1";

        //    //// try to open the selected port:
        //    //try
        //    //{
        //    //    port.Open();
               
        //    //}
        //    //// give a message, if the port is not available:
        //    //catch
        //    //{
        //    //    MessageBox.Show("Serial port " + port.PortName +
        //    //    "cannot be opened!", "RS232 tester",
        //    //    MessageBoxButtons.OK, MessageBoxIcon.Warning);
        //    //    comboBox1.SelectedText = "";
        //    //   // stsStatus.Text = "Select serial port!";
        //    //}
        //    ////port.Close();
        //}
        private void button2_Click(object sender, EventArgs e)
        {
            //port.Open();
            if (port.IsOpen) port.WriteLine(textBox2.Text);
            else MessageBox.Show("Serial port is closed!",
                                 "RS232 tester",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            textBox2.Clear();
            //port.Close();
        }
        private void button1_Click(object sender, EventArgs e)
        {
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }
        private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
        {
            InputData = port.ReadExisting();
            //byte[] receiveBuffer = new byte[128];
            //int bufferIndex = 0;
            //int bytesRead = 0;
            //int startPacketIndex = 0;
            //int expectedPacketLength = -1;
            //bool expectedPacketLengthIsSet = false;
            //int numBytesToRead = receiveBuffer.Length; 
            //bytesRead += port.Read(receiveBuffer, bufferIndex, numBytesToRead);
            if (InputData != String.Empty)
            {
                // txtIn.Text = InputData;
                // because of different threads this
                // does not work properly !!
                SetText(InputData);
            }
        }
        private void SetText(string text)
        {
            // InvokeRequired required compares the thread ID of the
            // calling thread to the thread ID of the creating thread.
            // If these threads are different, it returns true.
            if (this.textBox1.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                this.Invoke(d, new object[] { text });
            }
                else this.textBox1.Text += text;
        }
    }
}





plzzzzzzzzz help me ... i am in problem...

*** MOD EDIT: Fixed horrific code tags ***

Was This Post Helpful? 0
  • +
  • -

#5 eclipsed4utoo  Icon User is offline

  • Not Your Ordinary Programmer
  • member icon

Reputation: 1524
  • View blog
  • Posts: 5,960
  • Joined: 21-March 08

Re: How To Read Data From Serial Port

Posted 08 May 2009 - 05:47 AM

you should probably follow my snippet a little better. When you receive data in the DataReceived event, that is when you call the delegate.

namespace SerialPort
{
    public partial class ReadSample3 : Form
    {
        string InputData = String.Empty;
        System.IO.Ports.SerialPort port = new System.IO.Ports.SerialPort();
        delegate void SetTextCallback(string text);
        public ReadSample3()
        {
            InitializeComponent();
            
            port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
          
        }
        private void ReadSample3_Load(object sender, EventArgs e)
        {
            if (port.IsOpen)
                port.PortName = "COM1";
            
            // try to open the selected port:
            try
            {
               port.PortName = "COM1";

                port.BaudRate = 9600;
                port.DataBits = 8;
                port.Parity = Parity.None;
                port.StopBits = StopBits.One;
                port.DtrEnable = true;
                port.Handshake = Handshake.None;
                port.DtrEnable = true;
                port.Open();
            }
            // give a message, if the port is not available:
            catch
            {
                MessageBox.Show("Serial port " + port.PortName +
                "cannot be opened!", "RS232 tester",
                MessageBoxButtons.OK, MessageBoxIcon.Warning);
                
            }
        }
        
        private void button2_Click(object sender, EventArgs e)
        {
            
            if (port.IsOpen) port.WriteLine(textBox2.Text);
            else MessageBox.Show("Serial port is closed!",
                                 "RS232 tester",
                                 MessageBoxButtons.OK,
                                 MessageBoxIcon.Error);
            textBox2.Clear();
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
        port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived_1);
        }
        private void port_DataReceived_1(object sender,SerialDataReceivedEventArgs e)
        {
            InputData = port.ReadExisting();
            
            if (InputData != String.Empty)
            {
                this.BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
            }
        }

        private void SetText(string text)
        {
            this.textBox1.Text += text;
        }
    }
}




that should work.
Was This Post Helpful? 0
  • +
  • -

#6 prabhakara85  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 08-May 09

Re: How To Read Data From Serial Port

Posted 09 May 2009 - 12:14 AM

Dear Sir,

Please Find the Below lines of code.. in asp.net we dont have begininvoke please find sp_DataReceived,First time i will get value.. after second click on the button weight is not displaying in the textbox..

Due to this i spent so much of time.. i didnt get any solution..

private delegate void SetTextDeleg(string text);

protected void GetWeight()
{
// Makes sure serial port is open before trying to write
try
{
#region Code For Weighing Machine
// all of the options for a serial device
// can be sent through the constructor of the SerialPort class
// PortName = "COM1", Baud Rate = 19200, Parity = None,
// Data Bits = 8, Stop Bits = One, Handshake = None
_serialPort = new SerialPort("COM1", 2400, Parity.None, 8, StopBits.One);



_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
#endregion


if (!_serialPort.IsOpen)
_serialPort.Open();

// _serialPort.Write("SI\r\n");
_serialPort.Write("w\r\n");




}
catch (Exception ex)
{
ex.ToString();
}


}


void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(500);
string data = _serialPort.ReadLine();
SetTextDeleg aa = new SetTextDeleg(si_DataReceived);
IAsyncResult async = aa.BeginInvoke(data.Trim(), null, null);
_serialPort.Close();
}
private void si_DataReceived(string data)
{

lblMsg.Text = data.Replace("+","");


}
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1