从RS232端口获取数据到C#应用程序

时间:2016-03-11 15:15:04

标签: c# serial-port

我有一个电子秤ASCELL I210。 我想用RS232串口从中获取重量信息。 我使用的代码对我有用,但问题是文本框反复从缓冲区获得相同的结果所以我添加了一个包含_serialPort.Close()的try catch。以及_serialPort.Dispose(); 注意:我试图只使用_serialPort.Close();但它也没有用 我得到了我想要的结果但是弹出一个窗口说uncontrolled expression in application ... the port is closed 如果是我可以解决问题的其他方式请告诉我该怎么做

public partial class Form1 : Form
{
    private SerialPort _serialPort;         //<-- declares a SerialPort Variable to be used throughout the form
    private const int BaudRate = 9600;      //<-- BaudRate Constant. 9600 seems to be the scale-units default value
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        string[] portNames = SerialPort.GetPortNames();     //<-- Reads all available comPorts
        foreach (var portName in portNames)
        {
            comboBox1.Items.Add(portName);                  //<-- Adds Ports to combobox
        }
        comboBox1.SelectedIndex = 0;                        //<-- Selects first entry (convenience purposes)
    }

    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
        {          
                while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
                {
                    textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());

                }

                try 
                { 
                   _serialPort.Close();

                    if (_serialPort != null)
                    {
                        _serialPort.Dispose();
                    }
                }
                catch (InvalidCastException e)
                {
                }
            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

            //<-- This block ensures that no exceptions happen
            if (_serialPort != null && _serialPort.IsOpen)
                _serialPort.Close();

            if (_serialPort != null)
            {
                _serialPort.Dispose();
            }
            //<-- End of Block

            _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);       //<-- Creates new SerialPort using the name selected in the combobox
            _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 void button2_Click(object sender, EventArgs e)
        {
            if (_serialPort.IsOpen)
            {
                _serialPort.Close();
                Startbutton.Enabled = true;
                stopbutton.Enabled = false;
                textBox1.ReadOnly = true;
            }
        }
    }
}

0 个答案:

没有答案