0

我正在尝试将人们从 DataTable 输入的值发送到微控制器,但是当我通过 TeraTerm 再次检查微控制器中的值时,我得到的结果是错误的。

图片 :在此处输入图像描述

这是我的网格初始化代码:

private void Form1_Load(object sender, EventArgs e)
{
    //Data table
    DataTable table = new DataTable();

    //Column
    table.Columns.Add("TPS");
    table.Columns.Add("500", typeof(float));
    table.Columns.Add("750", typeof(float));
    //Row
    table.Rows.Add("100%");
    table.Rows.Add("95%");
    table.Rows.Add("90%");

    //Data Grid View
    dtGridView.DataSource = table;

    //Set width
    dtGridView.Columns[0].Width = 40;
    dtGridView.Columns[1].Width = 40;
    dtGridView.Columns[2].Width = 40;

}

和发送:

private void btnSend_Click(object sender, EventArgs e)
{
    try
    {
        for (int i = 0; i < dtGridView.Rows.Count; i++)
            for (int j = 0; j < dtGridView.Columns.Count; j++)
            {
                object o = dtGridView.Rows[i].Cells[j].Value;

                if (P.IsOpen == true)
                {
                    P.WriteLine(o.ToString());
                    MessageBox.Show("Write succesfully!");
                    P.Close();
                }
            }
    }
    catch(Exception ex)
    {
        MessageBox.Show("Unable to write to COM port");
    }
}
4

3 回答 3

0

The issue if you're calling P.Close() after the first iteration as others have noted. Generally with serial communications after connect I would just keep the connection open until the user explicitly disconnected. I would recommend removing P.Close(); from the loop and instead adding a disconnect button that calls P.Close();.

This should simplify your code as well as the send button will only be concerned with writing data and not also managing the state of the serial communications.

于 2021-01-26T13:40:48.300 回答
0

谢谢大家,我成功发送了价值。但是如果我按照我的方式做,它会发送表格的每个值。现在我想点击按钮发送,我输入的所有值都会一次性发送。是无论如何都要做吗?

这里附上图片:在此处输入图片描述

于 2021-01-26T14:31:11.893 回答
0

当您运行此循环时:

for (int i = 0; i < dtGridView.Rows.Count; i++)
    for (int j = 0; j < dtGridView.Columns.Count; j++)
    {
        object o = dtGridView.Rows[i].Cells[j].Value;
        if (P.IsOpen == true)
        {
            P.WriteLine(o.ToString());
            MessageBox.Show("Write succesfully!");
            P.Close(); // <<<<<<<<<<<<<<<<<<< this close the connection immediately after 1st val.
        }
    }

而是尝试在循环后关闭它。

for (int i = 0; i < dtGridView.Rows.Count; i++)
    for (int j = 0; j < dtGridView.Columns.Count; j++)
    {
        object o = dtGridView.Rows[i].Cells[j].Value;
        if (P.IsOpen == true)
        {
            P.WriteLine(o.ToString());
            MessageBox.Show("Write succesfully!");
        }
    }

if (P.IsOpen == true)
   P.Close();             // like this
于 2021-01-26T13:22:56.233 回答