SerialPort encoding - how do I get 8 bit ASCII?

人走茶凉 提交于 2019-12-31 04:57:06

问题


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
    ParityReplace   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?


回答1:


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.




回答2:


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);



回答3:


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



来源:https://stackoverflow.com/questions/7178655/serialport-encoding-how-do-i-get-8-bit-ascii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!