是这样的串口调试程序:发送指令、接收返回值。每次发送完指令,点击接收,返回一些返回值,再点击接收,又返回一些,为什么不能一次返回完呢???代码如下:private void Form1_Load(object sender,EventArgs e) //窗体加载
{
serialPort1.PortName="COM4";
serialPort1.Baudrate=806400;
if(!serialPort1.IsOpen)
{
serialPort1.Open();
}
}private void button1_Click(object sender,EventArgs e) //发送指令
{
str="";
byte[] hex;
string command=textBox1.Text.Trim();
hex=strToHexByte(command); //指令必须以字节的形式发送,把字符串转换为字节
serialPort1.Write(hex,0,hex.Length);
}string str;
private void serialPort1_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte bufferStr=(byte)serialPort1.ReadByte();
stirng s=Convert.ToString(bufferStr,16);
if(s=="0")
{
str+=s+"0";
}
else if(s.Length==1)
{
str+="0"+s;
}
else
{
str+=s;
}
}private void button2_Click(object sender,EventArgs e) //接收返回值
{
if(str!=""&&str!=null)
{
textBox2.Text=str.ToUpper();
}
str="";
}
{
serialPort1.PortName="COM4";
serialPort1.Baudrate=806400;
if(!serialPort1.IsOpen)
{
serialPort1.Open();
}
}private void button1_Click(object sender,EventArgs e) //发送指令
{
str="";
byte[] hex;
string command=textBox1.Text.Trim();
hex=strToHexByte(command); //指令必须以字节的形式发送,把字符串转换为字节
serialPort1.Write(hex,0,hex.Length);
}string str;
private void serialPort1_DataReceived(object sender,System.IO.Ports.SerialDataReceivedEventArgs e)
{
byte bufferStr=(byte)serialPort1.ReadByte();
stirng s=Convert.ToString(bufferStr,16);
if(s=="0")
{
str+=s+"0";
}
else if(s.Length==1)
{
str+="0"+s;
}
else
{
str+=s;
}
}private void button2_Click(object sender,EventArgs e) //接收返回值
{
if(str!=""&&str!=null)
{
textBox2.Text=str.ToUpper();
}
str="";
}
接收缓冲区并没有填充多少数据,可能出现字节接收不完全的情况
com 端口最大缓冲区4096,标准com通信都一个大数据包是拆包连续发送
ReceivedBytesThreshold设置成数据包大小
Thread.sleep(500);
int l= serialPort1.BytesToRead;
List<byte> buffer = new List<byte>();
int tick = Environment.TickCount;
while(Environment.TickCount-tick<1000)//假设1秒内回应为正常。
{
int n = comm.BytesToRead;
if(n == 0 )
{
Thread.Sleep(10);
continue;
}
byte[] t = new byte[n];
comm.Read(t,0,n);
buffer.AddRange(t);
//这里检查buffer中有没有命令应答,没有则继续等,有则退出。
}
这种方式有效,目前我也是这么做的,,,可以调大 sleep 的值试试