开发者

Reading data from Mettler Toledo scale device using C#

开发者 https://www.devze.com 2023-03-17 15:57 出处:网络
I am reading data from a Mettler Toledo scale device by using C# code. Here is my complete code: private SerialPort port = new SerialPort(\"COM1\", 4800, Parity.None, 8, StopBits.One);

I am reading data from a Mettler Toledo scale device by using C# code.

Here is my complete code:

private SerialPort port = new SerialPort("COM1", 4800, Parity.None, 8, StopBits.One);

public Inwardsfrm()
{开发者_StackOverflow社区
    InitializeComponent();
    port.DtrEnable = true;
    port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
}

private void Inwardsfrm_Load(object sender, EventArgs e)
{
    if (port.IsOpen == false)
    try
    {
        port.Open();
    }
    catch (Exception oex)
    {
        MessageBox.Show(oex.ToString());
    }
}

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    this.Invoke(new EventHandler(DoUpdate));
}


private void DoUpdate(object s, EventArgs e)
{
    Thread.Sleep(30);
    string data = port.ReadExisting() + port.ReadExisting();
    try
    {
        richTextBox1.Text = data.Trim().Remove(0, 3);
    }
    catch (Exception f)
    {
        MessageBox.Show(f.Message.ToString());
    }
}

It's working fine and shows the result in a label named richTextBox1, but some time it gives the following error:

Index and count must refers to location with the string Parameter Name :Count

What is wrong? How can I fix it?


It seems that the problem is caused by the Remove() method, there are less then 3 chars left in data after Trim().

try:

 private void DoUpdate(object s, EventArgs e)
    {
        Thread.Sleep(30);
        string data = port.ReadExisting() + port.ReadExisting();
        if(data.Trim().Count() < 3)
            MessageBox.Show("data = " + data);
        else
        try
        {    
            richTextBox1.Text = data.Trim().Remove(0, 3);
        }
        catch (Exception f)
        {
            MessageBox.Show(f.Message.ToString());
        }
    }

That should help figure it out.

0

精彩评论

暂无评论...
验证码 换一张
取 消