串口返回无效数据

时间:2013-01-10 08:39:35

标签: c# .net encoding serial-port

我有一台使用串口连接到计算机的称重机。这是一台非常古老的机器,我们正在努力减轻它的重量并保存在数据库中 机器返回的重量包含一些无效字符,例如?,重量显示为??2?0,应该是02220

据我所知,它与网络搜索建议的结果有关。但我无法弄清楚到底是什么原因。

这是我的代码:

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    // This method will be called when there is data waiting in the port buffer
    // Read all the data waiting in the buffer
    // string data = comport.ReadExisting();
    // Display the text to the user in the Rich Text Box
    Log(LogMsgType1.Incoming, s); 
}

public void OpenThisPort()
{
    bool error = false;

    // If the port is open, close it
    if (comport.IsOpen)
    {
        comport.Close();
    }
    else
    {
        comport.BaudRate = int.Parse("1200");
        comport.DataBits = int.Parse("8");
        comport.StopBits = StopBits.One;
        comport.Parity = Parity.None;
        comport.PortName = "COM1";
        delStart = 0;
        delLength = 9;
        comport.RtsEnable = true;
        comport.DtrEnable = true;
        comport.Encoding = System.Text.Encoding.GetEncoding(28591);
    }  

如何确定将应用哪种编码? 知道我在这里缺少什么吗?

2 个答案:

答案 0 :(得分:5)

可能不是编码问题而是硬件错误。 尝试检测它:

    #region comPort_ErrorReceived
    /// <summary>
    /// This method will be called when there's data waiting in the buffer
    ///  and error occured.
    /// DisplayData is a custom method used for logging
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void comPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e)
    {
        SerialError sr = e.EventType;
        switch (sr)
        {
            case SerialError.Frame:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the hardware detected a framing error.\n", 45);
                break;
            case SerialError.Overrun:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " a character-buffer overrun has occurred. The next character is lost.\n", 46);
                break;
            case SerialError.RXOver:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " an input buffer overflow has occured. There is either no room in the input buffer,"
                    + " or a character was received after the End-Of-File (EOF) character.\n", 47);
                break;
            case SerialError.RXParity:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the hardware detected a parity error.\n", 48);
                break;
            case SerialError.TXFull:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " the application tried to transmit a character, but the output buffer was full.\n", 49);
                break;
            default:
                DisplayData(newLog, EventLogEntryType.Error, "On port " + comPort.PortName
                    + " an unknown error occurred.\n", 50);
                break;
        }
    }

乍一看它看起来像是框架错误,因为数据的一部分似乎是正确的。对于初学者,请确保您的电缆良好。您也可以尝试使用其他应用程序(例如putty)连接到您的设备。

同样以字节形式读取数据可能是一个好主意(然后您可以在显示之前将其转换为十六进制)。通过这种方式,您可以了解实际发送的内容。

private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int btr = comPort.BytesToRead;
byte[] comBuffer = new byte[btr];
comPort.Read(comBuffer, 0, btr);
Console.WriteLine(ByteToHex(comBuffer));
}

private string ByteToHex(byte[] comByte)
        {
            StringBuilder builder = new StringBuilder(comByte.Length * 3);
            foreach (byte data in comByte)
                builder.Append(Convert.ToString(data, 16).PadLeft(2, '0').PadRight(3, ' '));
            return builder.ToString().ToUpper();
        }

答案 1 :(得分:0)

我遇到了同样的问题。 尝试将DataBits更改为 7 ,将Parity更改为 Parity.Even ,然后它应该可以正常工作。