c# SerialPort 接收数据不连续
用的是别人的的程序,把数据的的读已经改为read或者readline读回来的数据用串口监视助手监视时发现数据,不是一起读回来的。中间老是有间隔。没截图,只有打出来了,请见谅:
假如接收01 02 03 04 05 06
01 02
//时间间隔
03 04 05 06
请问如何能吧数据全部一起读出,不出现上面的时间间隔情况。
PS:数据读出是对的,就是中间很多时间间隔,时间开销太大。
using System;
using System.Collections.Generic;
using System.Text;
using System.IO.Ports;
namespace Modbus_Poll_CS
{
class modbus
{
private SerialPort sp = new SerialPort();
public string modbusStatus;
#region Constructor / Deconstructor
public modbus()
{
}
~modbus()
{
}
#endregion
#region Open / Close Procedures
public bool Open(string portName, int baudRate, int databits, Parity parity, StopBits stopBits)
{
//Ensure port isn't already opened:
if (!sp.IsOpen)
{
//Assign desired settings to the serial port:
sp.PortName = portName;
sp.BaudRate = baudRate;
sp.DataBits = databits;
sp.Parity = parity;
sp.StopBits = stopBits;
//These timeouts are default and cannot be editted through the class at this point:
sp.ReadTimeout = 1000;
sp.WriteTimeout = 1000;
try
{
sp.Open();
}
catch (Exception err)
{
modbusStatus = "Error opening " + portName + ": " + err.Message;
return false;
}
modbusStatus = portName + " opened successfully";
return true;
}
else
{
modbusStatus = portName + " already opened";
return false;
}
}
public bool Close()
{
//Ensure port is opened before attempting to close:
if (sp.IsOpen)
{
try
{
sp.Close();
}
catch (Exception err)
{
modbusStatus = "Error closing " + sp.PortName + ": " + err.Message;
return false;
}
modbusStatus = sp.PortName + " closed successfully";
return true;
}
else
{
modbusStatus = sp.PortName + " is not open";
return false;
}
}
#endregion
#region CRC Computation
private void GetCRC(byte[] message, ref byte[] CRC)
{
//Function expects a modbus message of any length as well as a 2 byte CRC array in which to
//return the CRC values:
ushort CRCFull = 0xFFFF;
byte CRCHigh = 0xFF, CRCLow = 0xFF;
char CRCLSB;
for (int i = 0; i < (message.Length) - 2; i++)
{
CRCFull = (ushort)(CRCFull ^ message[i]);
for (int j = 0; j < 8; j++)
{
CRCLSB = (char)(CRCFull & 0x0001);
CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF);
if (CRCLSB == 1)
CRCFull = (ushort)(CRCFull ^ 0xA001);
}
}
CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
}
#endregion
#region Build Message
private void BuildMessage(byte address, byte type, ushort start, ushort registers, ref byte[] message)
{
//Array to receive CRC bytes:
byte[] CRC = new byte[2];
message[0] = address;
message[1] = type;
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
message[4] = (byte)(registers >> 8);
message[5] = (byte)registers;
GetCRC(message, ref CRC);
message[message.Length - 2] = CRC[0];
message[message.Length - 1] = CRC[1];
}
#endregion
#region Check Response
private bool CheckResponse(byte[] response)
{
//Perform a basic CRC check:
byte[] CRC = new byte[2];
GetCRC(response, ref CRC);
if (CRC[0] == response[response.Length - 2] && CRC[1] == response[response.Length - 1])
return true;
else
return false;
}
#endregion
#region Get Response
private void GetResponse(ref byte[] response)
{
//There is a bug in .Net 2.0 DataReceived Event that prevents people from using this
//event as an interrupt to handle data (it doesn't fire all of the time). Therefore
//we have to use the ReadByte command for a fixed length as it's been shown to be reliable.
for (int i = 0; i < response.Length; i++)
{
response[i] = (byte)(sp.ReadByte());
}
}
#endregion
#region Function 16 - Write Multiple Registers
public bool SendFc16(byte address, ushort start, ushort registers, short[] values)
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Message is 1 addr + 1 fcn + 2 start + 2 reg + 1 count + 2 * reg vals + 2 CRC
byte[] message = new byte[9 + 2 * registers];
//Function 16 response is fixed at 8 bytes
byte[] response = new byte[8];
//Add bytecount to message:
message[6] = (byte)(registers * 2);
//Put write values into message prior to sending:
for (int i = 0; i < registers; i++)
{
message[7 + 2 * i] = (byte)(values[i] >> 8);
message[8 + 2 * i] = (byte)(values[i]);
}
//Build outgoing message:
BuildMessage(address, (byte)16, start, registers, ref message);
//Send Modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse(ref response);
}
catch (Exception err)
{
modbusStatus = "Error in write event: " + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
modbusStatus = "Write successful";
return true;
}
else
{
modbusStatus = "CRC error";
return false;
}
}
else
{
modbusStatus = "Serial port not open";
return false;
}
}
#endregion
#region Function 3 - Read Registers
public bool SendFc3(byte address, ushort start, ushort registers, ref short[] values)
{
//Ensure port is open:
if (sp.IsOpen)
{
//Clear in/out buffers:
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
//Function 3 request is always 8 bytes:
byte[] message = new byte[8];
//Function 3 response buffer:
byte[] response = new byte[5 + 2 * registers];
//Build outgoing modbus message:
BuildMessage(address, (byte)3, start, registers, ref message);
//Send modbus message to Serial Port:
try
{
sp.Write(message, 0, message.Length);
GetResponse(ref response);
}
catch (Exception err)
{
modbusStatus = "Error in read event: " + err.Message;
return false;
}
//Evaluate message:
if (CheckResponse(response))
{
//Return requested register values:
for (int i = 0; i < (response.Length - 5) / 2; i++)
{
values[i] = response[2 * i + 3];
values[i] <<= 8;
values[i] += response[2 * i + 4];
}
modbusStatus = "Read successful";
return true;
}
else
{
modbusStatus = "CRC error";
return false;
}
}
else
{
modbusStatus = "Serial port not open";
return false;
}
}
#endregion
}
}
--------------------编程问答-------------------- 真恶心,居然没有人回 --------------------编程问答-------------------- 提问讲求方法,看看提问的艺术。csdn支持ubb,代码规范一下,否则一看就晕了,没耐心看的。
串口、usb、并口、网络、1394等都是流设备,数据是顺序发送的。你无法忽略那个时间,只能一次收一段,缓存起来,数据收完后,统一处理。如何缓存,你可以看看我的博客。
http://blog.csdn.net/wuyazhe/category/695097.aspx --------------------编程问答-------------------- 是不是你读的太快了,还没有等对方发送完,就读了部分数据 --------------------编程问答-------------------- 对于Modbus报文,先读取Modbus RTU报文长度,然后根据这个长度读取数据, 直到读慢数据,所以你每次能读到几个数据对使用没有什么大的影响。一般来说Framework自带的串口一般一次读取8个字节,对于长报文需要分多次读。 --------------------编程问答-------------------- 代码能不能重新贴一下?看着累人。通信协议能不能说一下? --------------------编程问答-------------------- 帮顶一下啊
我也遇到了这样的问题
请会的人
不要吝啬的啊
说出来
大家一起分享一下的啊
--------------------编程问答-------------------- 我也碰到过类似的问题,没别的方法解决,我的方法很笨拙但有效,回调函数不断把serialport上的数据读取到缓冲区,然后另一段程序从缓冲区内读取数据,
发送数据的时候,给数据的头部和尾部加上标志,比如!$之类的字符,根据这些标志来判断数据在哪里开始,是否完整等, --------------------编程问答-------------------- 正在学习,好像这个代码里面只有功能16 和功能3 。有没有人能把MODBUS的完整程序共享一下呢,我只是用来学习用一下。我的邮箱:cwsncq@126.com ,先谢谢了! --------------------编程问答-------------------- 能够把发的东西全部接收,证明程序没有问题,而是设计者的程序机制有问题。你可以考虑先把接收到的数据先收集,满足条件再进行处理
补充:.NET技术 , C#