开发者

SerialPort encoding - how do I get 8 bit ASCII?

开发者 https://www.devze.com 2023-03-30 04:40 出处:网络
I\'m having a problem with a program that communicates over a serial port. One of the characters it must send and receive is the degree symbol, ASCII 0xBF. It\'s been working fine for years now sudden

I'm having a problem with a program that communicates over a serial port. One of the characters it must send and receive is the degree symbol, ASCII 0xBF. It's been working fine for years now suddenly the serial port object has started dropping bit 7, so I get 0x3F instead of 0xBF.

I'm sure that this is something silly I've done because I've tinkered with my code in that area recenlty - however I cannot see what I've done that causes loss of the 8th bit.

My port gets initialized like this:

    BaudRate              9600  int  
    DataBits              8 int  
    DiscardNull true    bool
    DtrEnable             true  bool
    Encoding    {System.Text.ASCIIEncoding} System.Text.Encoding                  Handshake           None  System.IO.Ports.Handshake
    NewLine           "\n"  string
    Parity            None  System.IO.Ports.Parity
    Parity开发者_JS百科Replace   63  byte
    PortName              "COM4"    string
    ReadBufferSize  128 int
    ReadTimeout 250 int
    ReceivedBytesThreshold  1   int
    RtsEnable             true  bool
    StopBits              One   System.IO.Ports.StopBits
    WriteBufferSize 64  int
    WriteTimeout    1500    int

Any ideas how I restore the port to 8-bit operation?


Your problem is that ASCIIEncoding is a 7 bit encoding. You're looking for something that supports Extended ASCII.

The following will get you Codepage 1252.

System.Text.Encoding.GetEncoding(1252);

This will get you ISO 8859-1.

System.Text.Encoding.GetEncoding(28591);

Both of these are considered Extended ASCII and both contain symbols (mostly with the same byte representation) typically associated with this set, such as © , ¥ , and º . See the referenced links for more information about which characters are included in each encoding.


System.Text.ASCIIEncoding isn't the right encoding to use for 8-bit communication. Instead use e.g. the "ISO 8859-1 Latin 1; Western European (ISO)" code page:

port.Encoding = Encoding.GetEncoding(28591);


The degree symbol in both 1252 and 28591 appears to be xB0, not xBF.

0

精彩评论

暂无评论...
验证码 换一张
取 消