Serial Port Complete - Latest Microcontroller projects

(lily) #1
Using .NET’s SerialPort Class

 int charToRead;


charToRead = ComPort.selectedPort.ReadChar();
Console.WriteLine((char)(charToRead));

$



The .NET Framework defaults to UTF-16 encoding for most strings and char-
acters, but the default encoding for SerialPort objects is ASCIIEncoding. With
ASCIIEncoding, character codes in the range 00h–7Fh are identical to Unicode
UTF-8 characters, and all character codes from 80h to FFh transmit as question
marks (3Fh).
This example creates a String that contains five 16-bit characters and writes five
bytes (an 8-bit code for each character) to the SerialPort object:

 Dim textToSend As String = "hello"


Dim ascii As New System.Text.ASCIIEncoding()

myComPort.Encoding = ascii
myComPort.Write(textToSend)

 String textToSend = "hello";


System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();

myComPort.Encoding = ascii;
myComPort.Write(textToSend);
The transmitting computer stores the character “h” as a 16-bit value (0068h) in
the String textToSend. The Write method causes the character “h” to transmit
on the port as the low byte of the encoded character (68h). The other character
codes also transmit as single bytes. ASCIIEncoding is the default encoding, so
explicitly assigning ASCIIEncoding to the Encoding property is optional.
Free download pdf