通过串口/ RS232接收数据

时间:2017-04-28 11:36:56

标签: c# serial-port

我遇到通过串口接收数据的问题。

当我启动软件后打开设备时,我可以正确接收它。

但是,如果我这样做,反过来我得到一个错误,因为它捕获了中途收到的字符串。而且我不确定如何正确过滤它。

我接收数据的代码如下。

_serialPort = new SerialPort
            {
                PortName = comboBox1.Text,
                BaudRate = BaudRate,
                DataBits = 8,
                Parity = Parity.None,
                StopBits = StopBits.One,
                RtsEnable = true,
                DtrEnable = false,
                WriteBufferSize = 2048,
                ReadBufferSize = 2048,
                ReceivedBytesThreshold = 13,
                ReadTimeout = 5000,
            };
            _serialPort.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort
            _serialPort.Open();     //<-- make the comport listen
            textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
        }

        private delegate void Closure();
        private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
        {


            if (InvokeRequired)     //<-- Makes sure the function is invoked to work properly in the UI-Thread
                BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself
            else
            {
               // int dataLength = 11;
                //int dataLength = _serialPort.BytesToRead;
                byte[] data = new byte[13];
                int nbrDataRead = _serialPort.Read(data, 0, 13);
                if (nbrDataRead == 0)
                    return;

                str = System.Text.Encoding.UTF8.GetString(data);
                WriteLog2();
            }
        }private void WriteLog2()
    {

        string path3 = @"c:\Scale Logs\Current Logs";
        string path4 = @"c:\Scale Logs\Current Logs\temp Log2.txt";
        bool folderExists = Directory.Exists(path3);
        if (!folderExists)
            Directory.CreateDirectory(path3);
        if (!File.Exists(path4))
        {
            File.Create(path4);
            using (var tw2 = new StreamWriter(path4, true))
            {
                if (ammountoflines < 10)
                {
                    tw2.WriteLine();
                    // tw2.WriteLine(str);
                    tw2.WriteLine(str);
                    tw2.WriteLine();
                    tw2.Close();
                    ammountoflines = ammountoflines + 1;
                    //averageweight = averageweight + weight;
                }
                else
                {
                    tw2.Close();
                    averageweight = (averageweight / 10);
                    System.IO.File.WriteAllText(@"c:\Scale Logs\Current Logs\temp Log2.txt", string.Empty);
                    ammountoflines = 0;
                    ready = "no";

                }
            }
        }
        else if (File.Exists(path4))
        {
            using (var tw2 = new StreamWriter(path4, true))
            {
                if (ready == "no")
                {
                    str = str.Replace("k", string.Empty);
                    str = str.Replace("g", string.Empty);
                    // str = str.Replace("0", string.Empty);
                    str = str.Replace("W", string.Empty);
                    str = str.Replace("G", string.Empty);
                    str = str.Replace(".", string.Empty);
                    str = str.Replace("\r\n", string.Empty);

                    if (Convert.ToInt32(str) < 1000 )
                    {
                        ready = "yes";
                    }
                }
                else
                {
                    //if (ammountoflines < 3)



                        str = str.Replace("k", string.Empty);
                        str = str.Replace("g", string.Empty);
                       // str = str.Replace("0", string.Empty);
                        str = str.Replace("W", string.Empty);
                        str = str.Replace("G", string.Empty);
                        str = str.Replace(".", string.Empty);
                        str = str.Replace("\r\n", string.Empty);

                        //MessageBox.Show(str);
                        //weight = Convert.ToInt32(str);
                        //MessageBox.Show(Convert.ToString(weight));
                        label3.Text = str;
                        weight = Convert.ToInt32(str);
                        if (weight > 1000)
                        {
                            if (weight < 3500)
                            {
                                tw2.WriteLine(str);
                                tw2.Close();
                                ammountoflines = ammountoflines + 1;
                                averageweight = weight;
                                ave = (decimal)averageweight / 100;
                            WriteLog();


                            //System.IO.File.WriteAllText(@"c:\Scale Logs\Current Logs\temp Log2.txt", string.Empty);

                        }
                        }
                        else
                        {

                        }




                }
            }
        }
    }

我收到的字符串是WG00000.0kg。如果在软件启动后打开设备,它可以正常工作。但如果它反过来我会得到一个完全混乱的字符串。

有没有办法在WG启动之前不读取数据?问题是由设备连续发送数据引起的。而且不仅在被触发时。所以我中途赶上了小溪。

0 个答案:

没有答案