1 Replies - 3578 Views - Last Post: 30 March 2012 - 06:02 PM Rate Topic: -----

#1 Fideon   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 30-March 12

Correct usage of the SerialPort.Read Method.

Posted 30 March 2012 - 02:45 PM

Hello everybody.

I have been trying to make a code that can retrieve an array of characters that I receive from a device connected to my computer through a Serial Port and find out if that array contains a non-printable character, then turn into string and print it, something like the Hercules program does with the Special Cchars option. But I just can't seem to get it right. Whenever I run my code all it shows is System.Char[] repeatedly. I've tried using the SerialPort.ReadLine() but it reads a string not the characters so it doesn't provide me with the non-printbale characters so I can retrieve them. I've already investigated regular expressions and the Match variable type, but by the looks of it I'm going to be using this after I can retrieve the array correctly.

Here's my code:
while (serialPortCOM3.BytesToRead > 0)
                    {
                        char[] serialmsg = new char[10000];
                        serialPortCOM3.Read(serialmsg, 0, SerialPortCOM3.ReadBufferSize);
                        messagesBox.Text += (serialmsg + "\r");
                    }



Could you please tell me what am I doing wrong and what can I do to fix it? Thanks a lot!

Is This A Good Question/Topic? 0
  • +

Replies To: Correct usage of the SerialPort.Read Method.

#2 tlhIn`toq   User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6535
  • View blog
  • Posts: 14,450
  • Joined: 02-June 10

Re: Correct usage of the SerialPort.Read Method.

Posted 30 March 2012 - 06:02 PM

Serial port tutorial: FAQ 12. (Click the SHOW button below)


TOP most asked:


What does this error message mean?

FAQ 2: How do I debug
FAQ 3: How do I make Class1/Form1 talk to Class2/Form2


FAQ (Frequently Asked Questions - Updated Mar 2012
Spoiler




Quote

Whenever I run my code all it shows is System.Char[] repeatedly.


You need to convert the char[] to a string first.
Trying to put the char[] into the .Text property is like saying
textbox1.Text = Button5;
The argument is not convertable to a string, so what you get is the TYPE turned into a string.

Then there is the whole matter of pre-defining a char[] a thousand long when you don't know the size of what you are reading. Bad form.

Or use the .Read instead of .ReadLIne or .ReadExisting which are better methods.

The tutorials I pointed out to you will help a lot in your understanding of the serialport.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1