我写了一个串口程序,前一段时间可以用,现在只能接收到虚拟串口发送的数据,实串口根本就进不了中断程序
各位高手,这是什么原因呀  ~0_0~

解决方案 »

  1.   

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO.Ports;
    using System.IO;
    using System.Collections;namespace sPort
    {
       /// <summary>
       /// 串口发送与接简化操作类
       /// </summary>
        public class SerPort
        {
            #region//数据定义        private SerialPort sPort;
            private byte[] ReceiveHeadByte;      //定义接收数据的头信息
            private uint ReceiveHeadByteLength;  //定义需要接收的有效数据长度
            private bool IsAddDataLength;       //定义是否在接收头信息的添加一个数据长度位
            private byte[] tempBuffer;          //定义一个临时缓冲区
            private byte[] readBuffer;          //定义一个接收读取缓冲区
            private bool IsHexReceive;          //定义是否十六进制接收               private uint Fhead_Index = 0;       //定义当前正在读取的字节标号,并与接收数据的头信息相匹配        #endregion        #region//串口参数设置        /// <summary>
            /// 类构造
            /// </summary>
            /// <param name="sport">传入一个串口控件</param>
            public SerPort(SerialPort sport)
            {
                sPort = sport;            
                ReceiveHeadByte = null;
                ReceiveHeadByteLength = 0;
                IsAddDataLength = false;
                IsHexReceive = true;
                tempBuffer = null;
                readBuffer = null;
                
                sport.DataReceived += new SerialDataReceivedEventHandler(sPort__DataReceived);
            }        /// <summary>
            /// 类构造
            /// </summary>
            /// <param name="sport">传入一个串口控件</param>
            /// <param name="receivHeadByte">接收的头信息</param>       
            public SerPort(SerialPort sport, byte[] receivHeadByte)
            {
                sPort = sport;
                if (receivHeadByte != null)
                {
                    ReceiveHeadByte = receivHeadByte;
                    ReceiveHeadByteLength = (uint)ReceiveHeadByte.Length - 1;
                }
                IsAddDataLength = false;
                IsHexReceive = true;
                tempBuffer = null;
                readBuffer = null;            sport.DataReceived += new SerialDataReceivedEventHandler(sPort__DataReceived);
            }        /// <summary>
            /// 类构造
            /// </summary>
            /// <param name="sport">传入一个串口控件</param>
            /// <param name="isHexReceive">是否十六进制接收</param>       
            public SerPort(SerialPort sport, bool isHexReceive)
            {
                sPort = sport;
                ReceiveHeadByte = null;
                ReceiveHeadByteLength = 0;
                IsAddDataLength = false;
                IsHexReceive = isHexReceive;
                tempBuffer = null;
                readBuffer = null;            sport.DataReceived += new SerialDataReceivedEventHandler(sPort__DataReceived);
            }        /// <summary>
            /// 类构造
            /// </summary>
            /// <param name="sport">传入一个串口控件</param>
            /// <param name="receivHeadByte">接收的头信息</param>
            /// <param name="isAddDataLength">在头信息后是否有数据长度</param>
            /// <param name="isHexReceive">是否十六进制接收</param>
            public SerPort(SerialPort sport,byte[] receivHeadByte,bool isAddDataLength,bool isHexReceive)
            {
                sPort = sport;
                if (receivHeadByte != null)
                {
                    ReceiveHeadByte = receivHeadByte;
                    ReceiveHeadByteLength = (uint)ReceiveHeadByte.Length - 1;
                    tempBuffer = new byte[ReceiveHeadByte.Length];
                }
                IsAddDataLength = isAddDataLength;
                IsHexReceive = isHexReceive;
                
                readBuffer = null;            sport.DataReceived += new SerialDataReceivedEventHandler(sPort__DataReceived);
            }       /// <summary>
           /// 初始化串呢
           /// </summary>
            public SerialPort InitsPort
            {
                set { sPort = value; }
                get { return sPort; }
            }        /// <summary>
            /// 获取当前可用串口列表并排序
            /// </summary>
            /// <returns>以列表形式返回</returns>
            public ArrayList GetPortList()
            {
                string[] list = SerialPort.GetPortNames();
                Array.Sort<string>(list);
                return ArrayList.Adapter(list);
            }        /// <summary>
            /// 设置或获取串口是否在头信息后添加数据长度
            /// </summary>
            public bool SetIsAddDataLength
            {
                set { IsAddDataLength = value; }
                get { return IsAddDataLength; }
            }        /// <summary>
            /// 设置或获取串口的头信息
            /// </summary>
            public byte[] SetReceiveHeadStr
            {
                set 
                { 
                    ReceiveHeadByte = value;
                    ReceiveHeadByteLength = (uint)(ReceiveHeadByte.Length - 1);
                    tempBuffer = new byte[ReceiveHeadByte.Length];
                }
                get { return ReceiveHeadByte; }
            }
      

  2.   

    /// <summary>
            /// 开启串口
            /// </summary>
            /// <returns></returns>
            public bool OpensPort()
            {
                bool back = false;
                if (!sPort.IsOpen)
                {
                    try
                    {
                        sPort.Open();
                        back = true;
                    }
                    catch(Exception)
                    { 
                        back = false;                    
                        throw new Exception(string.Format("端口 {0} 打开错误!",sPort.PortName));
                    }
                }
                else 
                    back = true;
                return back;
            }        /// <summary>
            /// 关闭串口
            /// </summary>
            /// <returns></returns>
            public bool ClosesPort()
            {
                bool back = false;
                if (sPort.IsOpen)
                {
                    try
                    {
                        sPort.Close();
                        back = true;
                    }
                    catch
                    { back = false; }            }
                else
                    back = true;
                return back;
            }        /// <summary>
            /// 设置或获取串口的串口名
            /// </summary>
            public string sPortName
            {            
                set 
                {
                    if (sPort.IsOpen)
                    {
                        try
                        {
                            sPort.Close();
                            sPort.PortName = value.ToString();
                            sPort.Open();
                        }
                        catch
                        { throw new ExecutionEngineException(string.Format("端口 {0} 打开错误!", value.ToString())); }
                    }
                    else
                        sPort.PortName = value.ToString(); 
                }
                get { return sPort.PortName.ToString(); }
            }        /// <summary>
            /// 设置或获取串口的波特率
            /// </summary>
            public int sPortBauRate
            {
                set
                {
                    if (sPort.IsOpen)
                    {
                        try
                        {
                            sPort.Close();
                            sPort.BaudRate = value; 
                            sPort.Open();
                        }
                        catch
                        { throw new ExecutionEngineException(string.Format("端口 {0} 打开错误!", value.ToString())); }
                    }
                    else
                        sPort.BaudRate = value; 
                }
                get { return sPort.BaudRate; }
            }        /// <summary>
            /// 设置或获取串口的校验位
            /// </summary>
            public Parity sPortParity
            {
                set
                {
                    if (sPort.IsOpen)
                    {
                        try
                        {
                            sPort.Close();
                            sPort.Parity = value; 
                            sPort.Open();
                        }
                        catch
                        { throw new ExecutionEngineException(string.Format("端口 {0} 打开错误!", value.ToString())); }
                    }
                    else
                        sPort.Parity = value; 
                }
                get { return sPort.Parity; }
            }        /// <summary>
            /// 设置或获取串口的停止位
            /// </summary>
            public StopBits sPortStopBits
            {
                set
                {
                    if (sPort.IsOpen)
                    {
                        try
                        {
                            sPort.Close();
                            sPort.StopBits = value; 
                            sPort.Open();
                        }
                        catch
                        { throw new ExecutionEngineException(string.Format("端口 {0} 打开错误!", value.ToString())); }
                    }
                    else
                        sPort.StopBits = value; 
                }
                get { return sPort.StopBits; }
            }        /// <summary>
            /// 设置或获取串口的数据位
            /// </summary>
            public int sPortDataBits
            {
                set
                {
                    if (sPort.IsOpen)
                    {
                        try
                        {
                            sPort.Close();
                            sPort.DataBits = value; 
                            sPort.Open();
                        }
                        catch
                        { throw new ExecutionEngineException(string.Format("端口 {0} 打开错误!", value.ToString())); }
                    }
                    else
                        sPort.DataBits = value; 
                }
                get { return sPort.DataBits; }
            }        /// <summary>
            /// 获取或设置是否十六进制接收
            /// </summary>
            public bool SetIsHexReceive
            {
                set { IsHexReceive = value; }
                get { return IsHexReceive; }
            }        #endregion        #region//串口数据发送        /// <summary>
            /// 串口发送数据
            /// </summary>
            /// <param name="data">待发送的数据字符串</param>
            /// <param name="IsHexSend">是否十六进制发送</param>
            /// <returns>发送结果标志</returns>
            public bool sPortSend(string data, bool IsHexSend)
            {
                bool back = false;
                if (IsHexSend)
                { 
                    string[] cut = data.Split(' ');
                    int len = cut.Length;
                    byte[] sendbyte = new byte[len];
                    for (int i = 0; i < len; i++)
                    {
                        try
                        {
                            sendbyte[i] = Convert.ToByte(cut[i], 16);
                        }
                        catch
                        {
                            back = false;
                            throw new Exception(string.Format("你输入的字符有非法字符,请先核对!"));
                        }
                    }
                    try
                    {
                        back = sPortSend(sendbyte);
                    }
                    catch (Exception ee)
                    {
                        throw new Exception(ee.Message);
                    }
                }
                else
                {
                    try
                    {
                        back = sPortSend(data);
                    }
                    catch (Exception ee)
                    {
                        throw new Exception(ee.Message);
                    }
                }
                return back;
            }        /// <summary>
            /// 发送字符串
            /// </summary>
            /// <param name="data">待发送的数据字符串</param>
            /// <returns>发送结果标志</returns>
            public bool sPortSend(string data)
            {
                bool back = false;
                try
                {
                    sPort.Write(data);
                    back = true;
                }
                catch(Exception ee)
                { 
                    back = false;
                    throw new Exception(ee.Message);
                }
                return back;
            }        /// <summary>
            /// 发送字节数据
            /// </summary>
            /// <param name="data">待发送的字节数据</param>
            /// <returns>发送结果标志</returns>
            public bool sPortSend(byte[] data)
            {
                bool back = false;
                try
                {
                    sPort.Write(data, 0, data.Length);
                    back = true;
                }
                catch(Exception ee)
                { 
                    back = false;
                    throw new Exception(ee.Message);
                }
                return back;
            }        #endregion        #region//定义委托与事件        /// <summary>
            /// 定义一个委托处理串口接收
            /// </summary>
            /// <param name="data"></param>
            public delegate void ReceiveHandle(object data);
            /// <summary>
            /// 定义一个委托事件处理串口接收
            /// </summary>
            public event ReceiveHandle ReceiveData;        #endregion
      

  3.   

    #region//串口数据接收        /// <summary>
            /// 串口接收
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void sPort__DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
                if (IsHexReceive == true)//十六进制接收模式
                {
                    if (ReceiveHeadByte != null && ReceiveHeadByte.Length > 0)
                    {
                        ReceiveData_HeadStr();
                    }
                    else
                    {
                        ReceiveData_NoHeadStr();
                    }
                    readBuffer = null;
                }
                else//字符接收模式
                {
                    ReceiveData_Char();
                }
            }        /// <summary>
            /// 字符接收模式
            /// </summary>
            private void ReceiveData_Char()
            {
                int count = sPort.BytesToRead;
                char[] recChars = new char[count];
                sPort.Read(recChars, 0, count);
                string recString = "";
                for (int i = 0; i < count; i++)
                {
                    recString += recChars[i].ToString();
                }
                recChars = null;
                ReceiveData(recString);
                recString = null;
            }        /// <summary>
            /// 无信息头接收模式
            /// </summary>
            private void ReceiveData_NoHeadStr()
            {
                int bufferlen = sPort.BytesToRead;
                readBuffer = new byte[bufferlen];
                sPort.Read(readBuffer, 0, bufferlen);
                ReceiveData(readBuffer);
                readBuffer = null;
            }        /// <summary>
            /// 有信息头接收模式
            /// </summary>
            private void ReceiveData_HeadStr()
            {
                int len = sPort.BytesToRead;
                readBuffer = new byte[len];
                sPort.Read(readBuffer, 0, len);         reBack:
                len = readBuffer.Length;//重置
                if (IsAddDataLength == true)//如果有在头信息后加长度
                {
                    int i = 0;
                    while (i < len)
                    {
                        if (JudgeIsReceiveHead(readBuffer[i]) == true)//判断是否接到头信息
                        {
                            byte datacount = readBuffer[i + 1];//取数据长度
                            byte bufferlen = (byte)(len - (i + 1) - 1);//缓冲区剩余数据长度
                            byte[] backByte = new byte[datacount + ReceiveHeadByte.Length + 1];
                            if (datacount <= bufferlen)
                            {
                                if (datacount == bufferlen)
                                {
                                    Array.Copy(readBuffer, i - (ReceiveHeadByteLength - 1), backByte, 0, ReceiveHeadByteLength + 1);
                                    ReceiveData(backByte);//响应事件
                                    backByte = null;
                                    readBuffer =null;
                                    return;
                                }
                                else//缓冲区剩余长度大于需接收数据长度
                                {
                                    Array.Copy(readBuffer, i - (ReceiveHeadByteLength - 1), backByte, 0, ReceiveHeadByteLength + 1);
                                    ReceiveData(backByte);//响应事件
                                    backByte = null;                                //剩余数据转移
                                    byte[] dbuffer = new byte[len - (ReceiveHeadByte.Length + 1 + datacount)];
                                    Array.Copy(readBuffer, ReceiveHeadByte.Length + 1 + datacount, dbuffer, 0, dbuffer.Length);
                                    readBuffer = null;
                                    readBuffer = dbuffer;
                                    dbuffer = null;
                                    Fhead_Index = 0;
                                    goto reBack;
                                }
                            }                    }
                        i++;
                    }
                }
                else//信息头后未接数据长度模式
                {
                    int i = 0;
                    while (i < len)
                    {
                        if (JudgeIsReceiveHead(readBuffer[i]) == true)//判断是否接到头信息
                        {
                            int dcount = len - (i - (int)ReceiveHeadByteLength);
                            byte[] backByte = new byte[dcount];                      
                            Array.Copy(readBuffer, i - (int)ReceiveHeadByteLength, backByte, 0, backByte.Length);
                            ReceiveData(backByte);
                            readBuffer = null;
                            backByte = null;
                            Fhead_Index = 0;
                            return;
                        }
                        i++;
                    } 
                    //tempBuffer = readBuffer;
                }
            }        /// <summary>
            /// 判断数据是否为头信息
            /// </summary>
            /// <param name="data">读取的当前一个字节</param>
            /// <returns></returns>
            private bool JudgeIsReceiveHead(byte data)
            {
                bool back = false;
                if (Fhead_Index < ReceiveHeadByteLength)
                    tempBuffer[Fhead_Index] = data;
                else
                {
                    if (Fhead_Index == (ReceiveHeadByteLength ))
                    {
                        tempBuffer[Fhead_Index] = data;
                        if (CheckHeadIsOK() == true)
                        {
                            back = true;
                        }
                        else
                        {
                            MoveTempBufferLeft();
                            back = false;
                        }
                    }
                    else
                    {
                        MoveTempBufferLeft();
                        Fhead_Index = ReceiveHeadByteLength ;
                        tempBuffer[Fhead_Index] = data;
                        back = CheckHeadIsOK();
                    }
                }
                Fhead_Index++;
                return back;
            }        /// <summary>
            /// 检测头信息是否匹配
            /// </summary>
            /// <returns></returns>
            private bool CheckHeadIsOK()
            {
                bool back=false;
                for (int i = 0; i < ReceiveHeadByteLength + 1; i++)
                {
                    if (ReceiveHeadByte[i] == tempBuffer[i])
                        back = true;
                    else
                    { back = false; break; }
                }
                return back;
            }        /// <summary>
            /// 向左移动不匹配的接收缓冲区
            /// </summary>
            private void MoveTempBufferLeft()
            {
                for (int i = 0; i < ReceiveHeadByteLength ; i++)
                {
                    tempBuffer[i] = tempBuffer[i + 1];
                }
            }        #endregion
        }
    }
      

  4.   

    已经解决,是串口硬件不同引起的,有的串口需要供电,我没有设置DtrEnable=true,导致Data_Received不能正常启动.