i am trying to get the sensor data from the Com Port.i used SerialDataReceivedEventArgs to get the comport data and stored it in a Queue.The data is coming continuously, so i used the backgroundWorker1_DoWork to dequeue data in parallel and store it in a file.The data format is as follows:

304,248,16260\n 344,124,16252\n

my issue is when i put the breakpoint after this statement string[] str = qdata.Dequeue().Split('\n'); to check if the data in str is same as data being received in qdata Queue.i found it is dissimilar. snapshot attached. enter image description here

str[0] does not have the same vale as the qdata[0] first character,as according to logic str[0] should contain 2.

why this is happening or i am doing something wrong please help. my code is as follows:

 private void button1_Click(object sender, EventArgs e)
        {
            string abc = comboBox1.SelectedItem.ToString();
            serialPort1.PortName = abc;
            serialPort1.BaudRate = 115200;
            serialPort1.Parity = Parity.None;
            serialPort1.Open();
            backgroundWorker1.RunWorkerAsync();
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(port_receiveddata);


        }
        public void port_receiveddata(object sender, SerialDataReceivedEventArgs e)
        {

            //data = serialPort1.ReadLine().ToString()+'\n';
            data = serialPort1.ReadExisting();
           // data = serialPort1.ReadLine();

            qdata.Enqueue(data);



        }

        private void button2_Click(object sender, EventArgs e)
        {
            serialPort1.Close();            
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            while ((serialPort1.IsOpen)||qdata.Count >0)
            {
                if (qdata.Count > 0)
                {
                    string[] str = qdata.Dequeue().Split('\n');
                    foreach (object item in str)
                    {
                        using (FileStream gf = new FileStream(temp, FileMode.Append, FileAccess.Write))
                        {
                            using (TextWriter pf = new StreamWriter(gf))
                            {
                                pf.Write(item);
                                pf.Write('\n');
                                pf.Close();
                            }
                        }
                    }                  
                }
            }
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (qdata.Count <=0)
            MessageBox.Show("complete");
        }

0 Answers