请教串口通讯DataReceived事件不触发的问题
我用vs2005写了一个串口监听程序,但是无法触发DataReceived事件,但是用调试工具是正常的,求各位大侠指教!
串口2/3交叉连接,4/6交叉连接,5/5直连,7/8交叉连接;源代码如下:
public SerialPort serialPort2; delegate void HandleInterfaceUpdateDelegate(string text); HandleInterfaceUpdateDelegate interfaceUpdateHandle; public Form1() { InitializeComponent(); InitCOM("COM1"); } /// <summary> /// 串口接收通信配置方法 /// </summary> /// <param name="PortName"></param> public void InitCOM(string PortName) { interfaceUpdateHandle = new HandleInterfaceUpdateDelegate(UpdateTextBox); //实例化委托对象 serialPort2 = new SerialPort(PortName, 2400, Parity.Odd, 8, StopBits.One); serialPort2.DataReceived += new SerialDataReceivedEventHandler(serialPort2_DataReceived);//DataReceived事件委托 serialPort2.ReceivedBytesThreshold = 1; serialPort2.RtsEnable = true; OpenPort(); label1.Text = label1.Text+serialPort2.PortName; label2.Text = label2.Text + serialPort2.BaudRate.ToString(); label3.Text = label3.Text + serialPort2.DataBits.ToString(); label4.Text = label4.Text + serialPort2.StopBits.ToString(); label5.Text = label5.Text + serialPort2.Parity.ToString(); } /// <summary> /// 数据显示方法 /// </summary> /// <param name="text"></param> private void UpdateTextBox(string text) { textBox1.Text = text; } /// <summary> /// 数据接收事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void serialPort2_DataReceived(object sender, SerialDataReceivedEventArgs e) { Thread.Sleep(2000); byte[] readBuffer = new byte[serialPort2.ReadBufferSize]; serialPort2.Read(readBuffer, 0, readBuffer.Length); this.Invoke(interfaceUpdateHandle, new string[] { Encoding.UTF8.GetString(readBuffer, 0, 100) }); } //public static 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(); //} //打开串口的方法 public void OpenPort() { try { serialPort2.Open(); } catch { } if (serialPort2.IsOpen) { Console.WriteLine("the port is opened!"); } else { Console.WriteLine("failure to open the port!"); } } //关闭串口的方法 public void ClosePort() { serialPort2.Close(); if (!serialPort2.IsOpen) { Console.WriteLine("the port is already closed!"); } } /// <summary> /// 窗体加载事件 /// </summary> /// <param name="sender">事件参数</param> /// <param name="e">窗体</param> private void Form1_Load(object sender, EventArgs e) { }