How to apply encoding when reading from a serial port

走远了吗. 提交于 2019-12-18 07:05:39

问题


I'm reading data from a serial port. I read this posting: http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/a709d698-5099-4e37-9e10-f66ff22cdd1e

He is writing about many of the issues I have encounter, but in his writing he refers to using: System.Text.Encoding.GetEncoding("Windows-1252"). The problem I'm having is when and how to apply this. There are three potitional spots in my opinion. When the serial port object is define:

private SerialPort comport = new SerialPort();

The Event handler:

comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

Or when reading the data:

string data = comport.ReadExisting();

No matter where I add it. I seem to get errors. How would one use Encoding?


回答1:


Instead of using ReadExisting, use the port's Read method to get the bytes and then convert them to a string with the desired encoding, like this:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    byte[] data = new byte[port.BytesToRead];
    port.Read(data, 0, data.Length);
    string s = Encoding.GetEncoding("Windows-1252").GetString(data);
}

Update: Here's a simpler, still-C#-2.0-friendly version based on João's answer. After you instantiate your SerialPort object, set its Encoding property like so:

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

Then your DataReceived method becomes just this:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    string s = port.ReadExisting();
}



回答2:


You should set the appropriate encoding before sending or receiving data, so the constructor is a good choice.

var sp = new SerialPort
{
    Encoding = Encoding.GetEncoding("Windows-1252")
};

If you still have problems receiving data after this you need to make sure that the data being sent to the serial port is in the encoding you specified ("Windows-1252").



来源:https://stackoverflow.com/questions/2714533/how-to-apply-encoding-when-reading-from-a-serial-port

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