SerialPort Encoding [Ryan Byington]

The SerialPort class uses the encoding specified by the SerialPort.Encoding property to convert strings and character arrays to bytes to send across the serial port. This encoding also gets used when reading from the serial port to convert bytes received by the serial port to strings and character arrays. <?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

By default the SerialPort class uses ASCII encoding which converts all characters with the value of 0-127 to a single byte with the same value. So “Hello” gets converted to the byte array {72, 101, 108, 108, 111}. However every other character gets converted to a byte with the value of 63 or the ‘?’ character. This applies for reading as well so if the serial port received the byte array {72, 101, 108, 108, 111} it will convert this to “Hello” and any byte with a value greater then 127 will get converted to the ‘?’ character.

 

The ASCII encoding works perfectly fine for most serial devices but there are still quite a few device that either send bytes with values beyond 127 or you need to send bytes with values greater then 127. You have two options; one would be to use the API’s that deal with byte[] and bypass the Encoding, or to use the correct Encoding. However finding the correct encoding is a bit tricky as most encodings that deal with values above 127 will use multiple bytes which probably won’t work with the device attached to the serial port. The only encoding that converts all characters with a value 0-255 to a single byte with the corresponding value and vice versa when converting bytes to characters is the “Western European (ISO)” encoding. Use the following code to use this Encoding with the SerialPort class:

 

            SerialPort mySerialPort = new SerialPort(“COM1”);

            mySerialPort.Encoding = Encoding.GetEncoding(28591);