Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is down I design a interface and I can not read my serial port please help me, where is the wrong ??

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;
using System.IO.Ports;
using System.Collections;



namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            string[] Ports = SerialPort.GetPortNames();//List comport
            foreach (string port in Ports)
            comboBox1.Items.Add(port);
                     
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)// serialport connection
        {
            if (button1.Text == "Connect")
            {
                try
                {
                    serialPort1.PortName = comboBox1.SelectedItem.ToString();
                    serialPort1.Open();
                    Button1.Text = "Disconnect";
                   

                }
                catch
                { };
                
            }
             else
                {
                serialPort1.Close();
                    Bağlan.Text="Connect";
                }
        }

       private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)// split the data 
        {
            serialPort1.ReadTimeout = 2000;
           

            while (true)
            {
                string mydata = serialPort1.ReadExisting();
                string[] splitdata = mydata.Split(',');
                int a = splitdata.Length;

                   

                if (serialPort1.IsOpen)
                {
                    for (int i = 0;i<a ; i++)// add data to listbox with this loop 
                    {
                        listBox1.Items.Add(splitdata[i]);
                        i++;
                        listBox2.Items.Add(splitdata[i]);
                        i++;
                        listBox3.Items.Add(splitdata[i]);
                        i++;
                        listBox4.Items.Add(splitdata[i]);
                        
                    }

                }
                else
                {
                    listBox1.Text = "ERROR";

                }

            }
           
        
            
                        

        }
    }

  
    
   
}
Posted
Comments
[no name] 13-Apr-14 4:24am    
How are you sending test data to this port. What baud rate etc. You never set any of this but use defaults. What are they? I can't tell you - do you know?
Huseyin_Akkaya 13-Apr-14 5:27am    
I tested my device with Arduino Program. Can you see my device options on this picture: http://i.hizliresim.com/YPjEy6.jpg

Oh, good grief...
You need to take a big step back and brush up on how Windows in general and Events in particular work.
Look at what you are doing:
C#
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)// split the data
 {
     serialPort1.ReadTimeout = 2000;
     while (true)
     {
         string mydata = serialPort1.ReadExisting();
         ...
     }
 }
As soon as you get the DataReceived event you will just sit in that loop forever, and it will probably never do anything you can see again...

You will get an event every time there is new data - you do not need to loop at all!
And you can't access controls directly from the DataRecieved event as it is not called on the UI thread - you would need to Invoke the controls or move the data to the UI thread first.
See here: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived(v=vs.110).aspx[^]
 
Share this answer
 
First of all: the ReadTimeout property should be setted once, i prefer just befor the opening action.

over the internet is full of snippet you could read, msdn has its own official way to read Serial Port, even if it ain't aiming to performance...

You should consider that the DataReceived event can be triggered every byte transferred so avoid to put a polling cycle in that method.

instead use a global variable (byte[] or string) for the main buffer, then in the dataReceived you add till the data reach your expected value.

C#
       public event EventHandler<SerialEventArgs> SerialEvent;

       public virtual void OnSerialEvent(SerialEventArgs e)
       {
           EventHandler<SerialEventArgs> handler = SerialEvent;
           if (handler != null)
           {
               handler(this, e);
           }
       }

       public class SerialEventArgs : EventArgs
       {
           private String evento;
           public String Evento { get { return evento; } }
           public SerialEventArgs(String e)
           {
               this.evento = e;
           }
       }

public void Ricevi(object sender, SerialDataReceivedEventArgs e)
       {
           buffer += serial.ReadExisting();
           if (buffer.Contains("\r\n"))
           {
              OnSerialEvent(new SerialEventArgs(buffer));
              buffer = "";
           }
       }


Beware of chunked data: there is no guarantee that the string ends with "\r\n" with ReadExisting, meanwhile the in the ReadLine method read till this special character(when they are, otherwise... bleee)

with this Event you can leave the entire management of the SerialPort object behind the scene and in your Form subscribe the custom event in here.

Hope this helps. Cheers!!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900