Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Whenever i send any ASCII value greater than 127 to the com port i get junk output values at the serial port.

 ComPort.Write(data);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
397 views
Welcome To Ask or Share your Answers For Others

1 Answer

Strictly speaking ASCII only contains 128 possible symbols.
You will need to use a different character set to send anything other than the 33 control characters and the 94 letters and symbols that are ASCII.

To make things more confusing, ASCII is used as a starting point for several larger (conflicting) character sets. This list is not comprehensive, but the most most common are:

  1. Extended_ASCII which is ASCII with 128 more characters in it.
  2. ISO 8859-1 is ASCII with all characters required to represent all Western European languages.
  3. Windows-1252 is ISO 8859-1 with a few alterations (including printable characters in the 0x80-0x9F range).
  4. ISO 8859-2 which is the equivalent for Eastern European languages.
  5. Windows-1250 is also for Eastern european languages, but bears little resemblance to 8859-2.
  6. UTF-8 is also derived from ASCII, but has different characters from 128 to 255.

Back to your problem: your encoding is set to ASCII, so you are prevented from sending any characters outside of that character set. You need to set your encoding to an appropriate character set for the data you are sending. In my experience (which is admittedly in USA and Western Europe) Windows-1252 is the most used.

In C#, you can send either a string or bytes through a Serial Port. If you send a string, it uses the SerialPort.Encoding to convert that string into bytes to send. You can set this to the appropriate encoding for your purposes, or you can manually convert convert a string with a System.Text.Encoding object.

Set the encoder on the com port:

ComPort.Encoding = Encoding.GetEncoding("Windows-1252");

or manually encode the string:

System.Text.Encoding enc = System.Text.Encoding.GetEncoding("Windows-1252");
byte[] sendBuffer = enc.GetBytes(command);
ComPort.write(sendBytes, 0, sendBuffer.Length);

both do functionally the same thing.


EDIT: 0x96 is a valid character in Windows-1252 This outputs a long hyphen. (normal hyphen is 0x2D)

System.Text.Encoding enc = System.Text.Encoding.GetEncoding("windows-1252");
byte[] buffer = new byte[]{0x96};
Console.WriteLine(enc.GetString(buffer));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...