Visual Studio windows form application C# serial communication receive data?

1.2k views Asked by At

I need a code that will receive serial data from arduino and display them in text boxes . I am receiving int type data separated by commas . Arduino serial data sample : 250,389,123,232,255,536,366,455,...

I need first six data to be displayed in six separate text boxes and then the consecutive data must replace the already existing values in those text boxes. I tried several times but everything went in vain. Some one help me.

1

There are 1 answers

0
Tomasz On BEST ANSWER

I assume you're using System.IO.Ports namespace and SerialPort class for communication. I also hope that BaudRate and other communication settings are as expected by the device.
If yes, then further if you receive the data repeatedly, you may capture it by using ReadTo method and giving it a comma as parameter. Such reading loop may look like this:

while(true) // replace it with some wiser condition
{
    string textRead = serialPort.ReadTo(",");
    // do the rest here
}

Now, you may also want to capture some larger amounts of data at once. Of course you can (say, capture 100 characters), but then you should:
- split the string with comma;
- leave the last item of string array (which will be the result of splitting method) and insert at 0 position of next received pack of characters;
- repeat those steps in loop like above.
Now, to the TextBox'es. If there are N of them and we take the first capturing method into account, you may do it like this:

TextBox[] tboxes = new TextBox[N]; // your number is 6, I know
int boxIndex = 0;
while(true) // again, use a reasonable condition
{
    string textRead = serialPort.ReadTo(",");
    tboxes[boxIndex].Text = textRead.Trim(',');
    if(++boxIndex >= tboxes.Length)
        boxIndex = 0;
}


This should do the job.