C# 4.0 C#和RS485/USB接收外来字符

C# 4.0 C#和RS485/USB接收外来字符,c#-4.0,usb,rs485,C# 4.0,Usb,Rs485,在我使用六个激光粒子计数器的项目中,当我发送命令时,总是返回无关字符。有时,以这种形式收到的字符串是不完整的。下面是一段代码:谁知道如何解决这个问题 /// <summary> /// Class to keep track of string and color for lines in output window. /// </summary> private class Line { public string Str; public Color F

在我使用六个激光粒子计数器的项目中,当我发送命令时,总是返回无关字符。有时,以这种形式收到的字符串是不完整的。下面是一段代码:谁知道如何解决这个问题

/// <summary>
/// Class to keep track of string and color for lines in output window.
/// </summary>
private class Line
{
    public string Str;
    public Color ForeColor;
    public Line(string str, Color color)
    {
        Str = str;
        ForeColor = color;
    }
}

ArrayList lines = new ArrayList();
    Font origFont;
    Font monoFont;

public Form1()
    {
        InitializeComponent();
        outputList_Initialize();
    Settings.Read();
        TopMost = Settings.Option.StayOnTop;

    CommPort com = CommPort.Instance;
        com.StatusChanged += OnStatusChanged;
        com.DataReceived += OnDataReceived;
        com.Open();
}

 #region Event handling - data received and status changed

    /// <summary>
    /// Prepare a string for output by converting non-printable characters.
    /// </summary>
    /// <param name="StringIn">input string to prepare.</param>
    /// <returns>output string.</returns>
    private String PrepareData(String StringIn)
    {
        // The names of the first 32 characters
        string[] charNames = {
            // "NUL", "SOH", "STX", "ETX", "EOT",
            //"ENQ", "ACK", "BEL", "BS", "TAB", "LF", "VT", "FF", "CR", "SO", "SI",
            //"DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB",
            //"ESC", "FS", "GS", "RS", "US", "Space"
                             };

        string StringOut = "";

        foreach (char c in StringIn)
        {
            if (Settings.Option.HexOutput)
            {
                StringOut = StringOut + String.Format("{0:X2} ", (int)c);
            }
            else if (c < 32 && c != 9)
            {
                StringOut = StringOut + "";// +"<"+charNames[c]+">";

                //Uglier "Termite" style
                //StringOut = StringOut + String.Format("[{0:X2}]", (int)c);
            }
            else
            {
                StringOut = StringOut + c;
            }
        }
        return StringOut;
    }

    /// <summary>
    /// Partial line for AddData().
    /// </summary>
    private Line partialLine = null;

    /// <summary>
    /// Add data to the output.
    /// </summary>
    /// <param name="StringIn"></param>
    /// <returns></returns>
    private Line AddData(String StringIn)
    {
        String StringOut = PrepareData(StringIn);

        // if we have a partial line, add to it.
        if (partialLine != null)
        {
            // tack it on
            partialLine.Str = partialLine.Str + StringOut;
            outputList_Update(partialLine);
            return partialLine;
        }

        return outputList_Add(StringOut, receivedColor);
    }

    // delegate used for Invoke
    internal delegate void StringDelegate(string data);

    /// <summary>
    /// Handle data received event from serial port.
    /// </summary>
    /// <param name="data">incoming data</param>
    public void OnDataReceived(string dataIn)
    {
        //Handle multi-threading
        if (InvokeRequired)
        {
            Invoke(new StringDelegate(OnDataReceived), new object[] { dataIn });
            return;
        }

        // pause scrolling to speed up output of multiple lines
        bool saveScrolling = scrolling;
        scrolling = false;

        // if we detect a line terminator, add line to output
        int index;
        while (dataIn.Length > 0 &&
            ((index = dataIn.IndexOf("\r")) != -1 ||
            (index = dataIn.IndexOf("\n")) != -1))
        {
            String StringIn = dataIn.Substring(0, index);
            dataIn = dataIn.Remove(0, index + 1);

            logFile_writeLine(AddData(StringIn).Str);
            logFile_writeLine1(AddData(StringIn).Str);
            partialLine = null; // terminate partial line
        }

        // if we have data remaining, add a partial line
        if (dataIn.Length > 0)
        {
            partialLine = AddData(dataIn);
        }

        // restore scrolling
        scrolling = saveScrolling;
        outputList_Scroll();
        listBox1_Scroll();
    }

    /// <summary>
    /// Update the connection status
    /// </summary>
    public void OnStatusChanged(string status)
    {
        //Handle multi-threading
        if (InvokeRequired)
        {
            Invoke(new StringDelegate(OnStatusChanged), new object[] { status });
            return;
        }
        textBox1.Text = status;
    }

    #endregion
//
///类来跟踪输出窗口中行的字符串和颜色。
/// 
私人班线
{
公共字符串Str;
公共色彩前景色;
公共行(字符串str,颜色)
{
Str=Str;
前景色=颜色;
}
}
ArrayList行=新的ArrayList();
字体起始字体;
字体单字体;
公共表格1()
{
初始化组件();
outputList_Initialize();
设置。读取();
TopMost=Settings.Option.StayOnTop;
CommPort com=CommPort.Instance;
com.StatusChanged+=OnStatusChanged;
com.DataReceived+=OnDataReceived;
com.Open();
}
#区域事件处理-收到数据并更改状态
/// 
///通过转换不可打印的字符为输出准备字符串。
/// 
///输入要准备的字符串。
///输出字符串。
私有字符串PrepareData(字符串StringIn)
{
//前32个字符的名称
字符串[]字符名={
//“NUL”、“SOH”、“STX”、“ETX”、“EOT”,
//“ENQ”、“ACK”、“BEL”、“BS”、“TAB”、“LF”、“VT”、“FF”、“CR”、“SO”、“SI”,
//“DLE”、“DC1”、“DC2”、“DC3”、“DC4”、“NAK”、“SYN”、“ETB”、“CAN”、“EM”、“SUB”,
//“ESC”、“FS”、“GS”、“RS”、“US”、“Space”
};
字符串StringOut=“”;
foreach(字符串中的字符c)
{
if(Settings.Option.HexOutput)
{
StringOut=StringOut+String.Format(“{0:X2}”,(int)c);
}
否则如果(c<32&&c!=9)
{
StringOut=StringOut+“”;//+“”;
//丑陋的“白蚁”风格
//StringOut=StringOut+String.Format(“[{0:X2}]”,(int)c);
}
其他的
{
断线=断线+c;
}
}
返回断线;
}
/// 
///AddData()的部分行。
/// 
专用行partialLine=null;
/// 
///向输出中添加数据。
/// 
/// 
/// 
专用行AddData(字符串StringIn)
{
串出=准备数据(串入);
//如果我们有一个部分行,添加到它。
if(partialLine!=null)
{
//把它钉上
partialLine.Str=partialLine.Str+StringOut;
输出列表_更新(partialLine);
返回部分线;
}
返回输出列表\u添加(StringOut,receivedColor);
}
//用于调用的委托
内部委托无效StringDelegate(字符串数据);
/// 
///处理从串行端口接收到的数据事件。
/// 
///传入数据
公共无效OnDataReceived(字符串数据输入)
{
//处理多线程
如果(需要调用)
{
调用(新StringDelegate(OnDataReceived),新对象[]{dataIn});
返回;
}
//暂停滚动以加速多行的输出
bool saveScrolling=滚动;
滚动=假;
//如果我们检测到一个行终止符,将行添加到输出
整数指数;
而(dataIn.Length>0&&
((index=dataIn.IndexOf(“\r”))!=-1||
(index=dataIn.IndexOf(“\n”)!=-1)
{
字符串StringIn=dataIn.Substring(0,索引);
dataIn=dataIn.Remove(0,索引+1);
日志文件_writeLine(AddData(StringIn).Str);
日志文件_writeLine1(AddData(StringIn).Str);
partialLine=null;//终止部分行
}
//如果有剩余数据,请添加部分行
如果(dataIn.Length>0)
{
partialLine=AddData(数据输入);
}
//恢复滚动
滚动=保存滚动;
outputList_Scroll();
listbox1u Scroll();
}
/// 
///更新连接状态
/// 
状态更改时的公共无效(字符串状态)
{
//处理多线程
如果(需要调用)
{
调用(新StringDelegate(OnStatusChanged),新对象[]{status});
返回;
}
textBox1.Text=状态;
}
#端区

可能是位(或字节)填充吗

我想是的,或者是等待时间的问题。有解决这个问题的办法吗?