Serial Port Complete - Latest Microcontroller projects

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

 Char charToSend = (char)169;


myComPort.Write(System.Convert.ToString(charToSend));
But if the transmitting port is using ASCIIEncoding, the port transmits 3Fh.
The receiving computer reads the character:

 Dim receivedChar As Char


receivedChar = ChrW(myComPort.ReadChar)
Console.WriteLine(receivedChar)

 Int32 receivedChar;


receivedChar = (myComPort.ReadChar());
Console.WriteLine(System.Convert.ToChar(receivedChar));
And the console output is:
?
To enable transmitting characters with character codes 80h–FFh, an application
can declare a different encoding. One option is UTF-8 encoding:

 Dim utf8 As New System.Text.UTF8Encoding()


myComPort.Encoding = utf8

 System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();


myComPort.Encoding = utf8;
With this encoding, the transmitted bytes don’t always match the code points of
the characters because UTF-8 encoding converts code points 80h–FFh to mul-
tiple 8-bit code units. If a computer using UTF-8 encoding communicates with
a computer using ASCIIEncoding or another encoding, the receiving computer
won’t decode the data correctly.
If the transmitting and receiving computers both use UTF8Encoding and run
the example code above, the transmitting computer converts the UTF-16 string
00A9h to the UTF-8 code units C2h A9h and transmits the two bytes on the
serial port. The receiving computer converts the received code units to the
UTF-16 String 00A9h and displays:
©
Free download pdf