简体   繁体   中英

C# read from serial port arduino

I have done a simple project that reads from serial port (arduino) and I receive the data and I can put those data in textbox, richtex but I cant put them in data grid in fact I need to put those data in MSSQL table but also display in data grid. here is the code that I have tried:

void _spManager_NewSerialDataRecieved(object sender, SerialDataEventArgs e)
        {
            if (this.InvokeRequired)
            {
                // Using this.Invoke causes deadlock when closing serial port, and BeginInvoke is good practice anyway.
                this.BeginInvoke(new EventHandler<SerialDataEventArgs>(_spManager_NewSerialDataRecieved), new object[] { sender, e });
                return;
            }

            int maxTextLength = 1000; // maximum text length in text box
            if (tbData.TextLength > maxTextLength)
                tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength);

            // This application is connected to a GPS sending ASCCI characters, so data is converted to text
            string str = Encoding.ASCII.GetString(e.Data);
            tbData.AppendText(str);
            tbData.ScrollToCaret();

             richD.AppendText(str);
                richD.ScrollToCaret();

             dataGridView1.DataSource = str;

            }

Can you help me fill the datagridbiew?

This is where I get the e.Data:

public class SerialDataEventArgs : EventArgs
{
    public SerialDataEventArgs(byte[] dataInByteArray)
    {
        Data = dataInByteArray;
    }

    /// <summary>
    /// Byte array containing data from serial port
    /// </summary>
    public byte[] Data;
}

this is your answer:

string[] array = imput.split();

you have error at str in fact when you recive data at str is a bit data not string.

change this code:

if (tbData.TextLength > maxTextLength)
                tbData.Text = tbData.Text.Remove(0, tbData.TextLength - maxTextLength);

            // This application is connected to a GPS sending ASCCI characters, so data is converted to text
            string str = Encoding.ASCII.GetString(e.Data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM