还是SerialPort控件的问题
我用3个Button实现 初始化 发送 接受 的功能
初始化
serialPort1.PortName = "com1";//选择串口COM1
serialPort1.BaudRate = 9600;//设置通信口参数
serialPort1.DataBits = 8;//数据位
serialPort1.Parity = Parity.None;//校验位 None
serialPort1.StopBits = StopBits.One;//停止位1位
发送
byte[] bytesData = {123,23};
if (!serialPort1.IsOpen)
{
serialPort1.Open();
serialPort1.Write(bytesData, 0, bytesData.Length);
}
接受
byte[] b = new byte[serialPort1.BytesToRead];
serialPort1.Read(b, 0, b.Length);
serialPort1.Close();
我想问下高手 为什么我在接受的时候b里没有数据呢?
------解决方案--------------------
你是发完了就收吗?发完了马上收对方的数据可能还没发上来。
以下是我写的一个串口通讯类,你可能实例化一下,直接调用serialPort.Write()发送数据了
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
using System.Data;
namespace Comm
{
public class CSerialPort : SerialPort
{
public delegate void ReceiveFinished(Object sender,ReceiveFinishedEventArgs e);
public event ReceiveFinished ReceiveFinishedEvent;
public class ReceiveFinishedEventArgs : EventArgs
{
public string outBuffer;
public ReceiveFinishedEventArgs(string outBuffer)
{
this.outBuffer = outBuffer;
}
}
public void OnReceiveFinished(ReceiveFinishedEventArgs e)
{
if (ReceiveFinishedEvent!=null)
{
ReceiveFinishedEvent(this,e);
}
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="portName">串口名称,如"COM1"</param>
public CSerialPort(string portName)
{
DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
this.ReceivedBytesThreshold = 1;
this.DtrEnable = true;
PortName = portName;
baudRate = 9600;
dataBits = 8;
parity = Parity.None;
stopBits = StopBits.One;
handShake = Handshake.None;
}
~CSerialPort()
{
Dispose();
}
public new void Dispose()
{
Close();
base.Dispose(true);
}
public void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string outBuffer ="";
while (this.BytesToRead > 0)
{
outBuffer += this.ReadExisting();
System.Threading.Thread.Sleep(400);
}
if (ReceiveFinishedEvent!=null)
{
ReceiveFinishedEventArgs ea = new ReceiveFinishedEventArgs(outBuffer);
OnReceiveFinished(ea);
}
}
/// <summary>
/// 串口号
/// </summary>
public string serialPortName
{
get
{
return PortName;
}
set
{
PortName = value;
}
}
/// <summary>
/// 波特率
/// </summary>
public int baudRate
{