我是新手,我自己写了个小程序,通过串口让电脑来读取机器上过来的测试铜线的数据,当机器测试完成后按一个键数据就可以传到我的程序并显示出来,但是当机器进行第2次测试的时候数据就传不过来了,怎么按键都没有反映,要我重启电脑后又可以接收该次的数据.就这样要重启一次才能接收一次数据,请问这是什么原因,是串口的设置问题还是什么?请大家帮忙,谢谢!

解决方案 »

  1.   

    主要代码如下:    private void Log(LogMsgType msgtype, string msg)
        {
          rtfTerminal.Invoke(new EventHandler(delegate
          {
            rtfTerminal.SelectedText = string.Empty;
            rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
            rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
            rtfTerminal.AppendText(msg);
            rtfTerminal.ScrollToCaret();
          }));
        }    /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
        /// <param name="s"> The string containing the hex digits (with or without spaces). </param>
        /// <returns> Returns an array of bytes. </returns>
        private byte[] HexStringToByteArray(string s)
        {
          s = s.Replace(" ", "");
          byte[] buffer = new byte[s.Length / 2];
          for (int i = 0; i < s.Length; i += 2)
            buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
          return buffer;
        }    /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
        /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
        /// <returns> Returns a well formatted string of hex digits with spacing. </returns>
        private string ByteArrayToHexString(byte[] data)
        {
          StringBuilder sb = new StringBuilder(data.Length * 3);
          foreach (byte b in data)
            sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
          return sb.ToString().ToUpper();
        }    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
          // This method will be called when there is data waiting in the port's buffer      // Determain which mode (string or binary) the user is in
          if (CurrentDataMode == DataMode.Text)
          {
            // Read all the data waiting in the buffer
            string data = comport.ReadExisting();        // Display the text to the user in the terminal
            Log(LogMsgType.Incoming, data);
          }
          else
          {
            // Obtain the number of bytes waiting in the port's buffer
            int bytes = comport.BytesToRead;        // Create a byte array buffer to hold the incoming data
            byte[] buffer = new byte[bytes];        // Read the data from the port and store it in our buffer
            comport.Read(buffer, 0, bytes);        // Show the user the incoming data in hex format
            Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
          }
        }    private void txtSendData_KeyDown(object sender, KeyEventArgs e)
        { 
          // If the user presses [ENTER], send the data now
          if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); } 
        }
        private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
        { e.Handled = KeyHandled; }
        #endregion
      }
    }
      

  2.   

    给你一段我的代码看看VS2005的,继承于  SerialPort
    //发送结束后把串口关闭,并把缓冲区的内容清除用下面的语句
                   this.DiscardInBuffer();
                    this.DiscardOutBuffer();                this.Close();
                    this.Dispose();
    //一个事例
        public bool[] SendYaFenTime(Write24H write24H)
            {
                //发送数据次数,超出寻检次数直接退出
                int[] sendCount = new int[workStationCount];            //分机发送成功标志,成功后不再对该分机发送数据
                bool[] isSuccess = new bool[workStationCount];            byte[] write = new byte[9];
                byte[] read = null;
                try
                {
                    for (int j = 0; j < cycleCount; j++)
                    {
                        Thread.Sleep(20);                    for (int i = 0; i < workStationCount; i++)
                        {
                            sendCount[i]++;
                            //如果该分机已经执行成功,就检测下一分机
                            if (isSuccess[i] || (sendCount[i] > cycleCount))
                            {
                                continue;
                            }
                            if (this.IsOpen)
                            {
                                this.Close();
                            }                        this.Open();                        //Thread.Sleep(20);                        write = ConvertCommData.Write_24H((byte)(i + 1), write24H);                        //发送数据
                            this.Write(write, 0, write.Length);                        //Thread.Sleep(20);                        //等待数据发送完成
                            do
                            {
                                //Application.DoEvents();
                                Thread.Sleep(20);
                            }
                            while (this.BytesToWrite != 0);
                            int startTime = Environment.TickCount;                        //延时
                            do
                            {
                                Thread.Sleep(20);
                            }
                            while (Environment.TickCount - startTime <= totalOverTime && this.BytesToRead < 5);                        //接收缓冲区的字符数
                            int readBuf = this.BytesToRead;                        if (readBuf < 5)
                            {
                                continue;
                            }
                            else
                            {
                                //接收数据
                                read = new byte[readBuf];
                                this.Read(read, 0, read.Length);                            //根据给定数组,计算CRC值
                                int CrcValue = CalculateCrc(read);                            //比较CRC值
                                if ((read[read.Length - 2] == (CrcValue & 0xFF)) && (read[read.Length - 1] == ((CrcValue >> 8) & 0xFF)))
                                {
                                    //数值接收正确
                                    isSuccess[i] = true;                                continue;
                                }
                                else
                                {
                                    //CRC校验错误
                                    continue;
                                }
                            }
                        }
                    }
                    return isSuccess;            }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                }
                finally
                {
                    this.DiscardInBuffer();
                    this.DiscardOutBuffer();                this.Close();
                    this.Dispose();
                }
            }
      

  3.   

    Q群 12757054 群主有请!  
    希望相关的.net开发者&&初学者家入(但是一定要经常的在线)  
     我要保证在线人数  
     能让大家的问题及时得到解决!  
    欢迎加入 共同进步!  
      

  4.   

    估计是第二次的时候进入 这个条件了 if (CurrentDataMode == DataMode.Text).楼主可以在第二次接收的时候在这里设个断点看看
      

  5.   

    2005没用过。不过在2003下使用MsComm.ocx好像没你说的问题。我以前在使用串口的时候我一搞单片机方面的同学给我建议就是在关闭和打开中断,防止出现中断嵌套。
      

  6.   

    学习中... 欢迎加入ASP.NET(C#)学习交流QQ群号:①32801051(已满) ②23222074(请不要两个群都加)
      

  7.   

    可惜,.net我一直是直接调用API进行串口操作的
      

  8.   

    to: 可惜,.net我一直是直接调用API进行串口操作的有代码可以参考吗
      

  9.   

    to: icefeiji(咖啡色的猪) 应该怎么写初始化的部分?我不太懂串口。
    还有好像我2台电脑用串口连接后,这个程序是正常工作的。
      

  10.   

    主要原因是你的串口参数设置同下位机的设置不相同,最容易忽略的是DTR,RTS,你换下参数试试
      

  11.   

    to: 主要原因是你的串口参数设置同下位机的设置不相同,最容易忽略的是DTR,RTS,你换下参数试试我对串口没有什么研究,我和负责机器的工程师讨论过,他说只要设置了9600,8,1,n几项就可以了。DTR和RTS具体是什么?
      

  12.   

    to zxf92183 :如果收发数据不是很快的话,比如说1s每次。
    你可以建立一个Timer。
    在Tick里面把所有的数据都读出来,然后分析数据显示。
    没必要一个数据一个数据的收,那样很麻烦。
      

  13.   

    我用2005 .net 的串口控件没问题
    因为数据是持续发送 所以也没清空缓冲区