主要代码如下: private void Log(LogMsgType msgtype, string msg) { rtfTerminal.Invoke(new EventHandler(delegate { rtfTerminal.SelectedText = string.Empty; rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold); rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype]; rtfTerminal.AppendText(msg); rtfTerminal.ScrollToCaret(); })); } /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary> /// <param name="s"> The string containing the hex digits (with or without spaces). </param> /// <returns> Returns an array of bytes. </returns> private byte[] HexStringToByteArray(string s) { s = s.Replace(" ", ""); byte[] buffer = new byte[s.Length / 2]; for (int i = 0; i < s.Length; i += 2) buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16); return buffer; } /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary> /// <param name="data"> The array of bytes to be translated into a string of hex digits. </param> /// <returns> Returns a well formatted string of hex digits with spacing. </returns> private 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(); } private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { // This method will be called when there is data waiting in the port's buffer // Determain which mode (string or binary) the user is in if (CurrentDataMode == DataMode.Text) { // Read all the data waiting in the buffer string data = comport.ReadExisting(); // Display the text to the user in the terminal Log(LogMsgType.Incoming, data); } else { // Obtain the number of bytes waiting in the port's buffer int bytes = comport.BytesToRead; // Create a byte array buffer to hold the incoming data byte[] buffer = new byte[bytes]; // Read the data from the port and store it in our buffer comport.Read(buffer, 0, bytes); // Show the user the incoming data in hex format Log(LogMsgType.Incoming, ByteArrayToHexString(buffer)); } } private void txtSendData_KeyDown(object sender, KeyEventArgs e) { // If the user presses [ENTER], send the data now if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); } } private void txtSendData_KeyPress(object sender, KeyPressEventArgs e) { e.Handled = KeyHandled; } #endregion } }
给你一段我的代码看看VS2005的,继承于 SerialPort //发送结束后把串口关闭,并把缓冲区的内容清除用下面的语句 this.DiscardInBuffer(); this.DiscardOutBuffer(); this.Close(); this.Dispose(); //一个事例 public bool[] SendYaFenTime(Write24H write24H) { //发送数据次数,超出寻检次数直接退出 int[] sendCount = new int[workStationCount]; //分机发送成功标志,成功后不再对该分机发送数据 bool[] isSuccess = new bool[workStationCount]; byte[] write = new byte[9]; byte[] read = null; try { for (int j = 0; j < cycleCount; j++) { Thread.Sleep(20); for (int i = 0; i < workStationCount; i++) { sendCount[i]++; //如果该分机已经执行成功,就检测下一分机 if (isSuccess[i] || (sendCount[i] > cycleCount)) { continue; } if (this.IsOpen) { this.Close(); } this.Open(); //Thread.Sleep(20); write = ConvertCommData.Write_24H((byte)(i + 1), write24H); //发送数据 this.Write(write, 0, write.Length); //Thread.Sleep(20); //等待数据发送完成 do { //Application.DoEvents(); Thread.Sleep(20); } while (this.BytesToWrite != 0); int startTime = Environment.TickCount; //延时 do { Thread.Sleep(20); } while (Environment.TickCount - startTime <= totalOverTime && this.BytesToRead < 5); //接收缓冲区的字符数 int readBuf = this.BytesToRead; if (readBuf < 5) { continue; } else { //接收数据 read = new byte[readBuf]; this.Read(read, 0, read.Length); //根据给定数组,计算CRC值 int CrcValue = CalculateCrc(read); //比较CRC值 if ((read[read.Length - 2] == (CrcValue & 0xFF)) && (read[read.Length - 1] == ((CrcValue >> 8) & 0xFF))) { //数值接收正确 isSuccess[i] = true; continue; } else { //CRC校验错误 continue; } } } } return isSuccess; } catch (Exception ex) { throw new Exception(ex.Message); } finally { this.DiscardInBuffer(); this.DiscardOutBuffer(); this.Close(); this.Dispose(); } }
{
rtfTerminal.Invoke(new EventHandler(delegate
{
rtfTerminal.SelectedText = string.Empty;
rtfTerminal.SelectionFont = new Font(rtfTerminal.SelectionFont, FontStyle.Bold);
rtfTerminal.SelectionColor = LogMsgTypeColor[(int)msgtype];
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();
}));
} /// <summary> Convert a string of hex digits (ex: E4 CA B2) to a byte array. </summary>
/// <param name="s"> The string containing the hex digits (with or without spaces). </param>
/// <returns> Returns an array of bytes. </returns>
private byte[] HexStringToByteArray(string s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
} /// <summary> Converts an array of bytes into a formatted string of hex digits (ex: E4 CA B2)</summary>
/// <param name="data"> The array of bytes to be translated into a string of hex digits. </param>
/// <returns> Returns a well formatted string of hex digits with spacing. </returns>
private 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();
} private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// This method will be called when there is data waiting in the port's buffer // Determain which mode (string or binary) the user is in
if (CurrentDataMode == DataMode.Text)
{
// Read all the data waiting in the buffer
string data = comport.ReadExisting(); // Display the text to the user in the terminal
Log(LogMsgType.Incoming, data);
}
else
{
// Obtain the number of bytes waiting in the port's buffer
int bytes = comport.BytesToRead; // Create a byte array buffer to hold the incoming data
byte[] buffer = new byte[bytes]; // Read the data from the port and store it in our buffer
comport.Read(buffer, 0, bytes); // Show the user the incoming data in hex format
Log(LogMsgType.Incoming, ByteArrayToHexString(buffer));
}
} private void txtSendData_KeyDown(object sender, KeyEventArgs e)
{
// If the user presses [ENTER], send the data now
if (KeyHandled = e.KeyCode == Keys.Enter) { e.Handled = true; SendData(); }
}
private void txtSendData_KeyPress(object sender, KeyPressEventArgs e)
{ e.Handled = KeyHandled; }
#endregion
}
}
//发送结束后把串口关闭,并把缓冲区的内容清除用下面的语句
this.DiscardInBuffer();
this.DiscardOutBuffer(); this.Close();
this.Dispose();
//一个事例
public bool[] SendYaFenTime(Write24H write24H)
{
//发送数据次数,超出寻检次数直接退出
int[] sendCount = new int[workStationCount]; //分机发送成功标志,成功后不再对该分机发送数据
bool[] isSuccess = new bool[workStationCount]; byte[] write = new byte[9];
byte[] read = null;
try
{
for (int j = 0; j < cycleCount; j++)
{
Thread.Sleep(20); for (int i = 0; i < workStationCount; i++)
{
sendCount[i]++;
//如果该分机已经执行成功,就检测下一分机
if (isSuccess[i] || (sendCount[i] > cycleCount))
{
continue;
}
if (this.IsOpen)
{
this.Close();
} this.Open(); //Thread.Sleep(20); write = ConvertCommData.Write_24H((byte)(i + 1), write24H); //发送数据
this.Write(write, 0, write.Length); //Thread.Sleep(20); //等待数据发送完成
do
{
//Application.DoEvents();
Thread.Sleep(20);
}
while (this.BytesToWrite != 0);
int startTime = Environment.TickCount; //延时
do
{
Thread.Sleep(20);
}
while (Environment.TickCount - startTime <= totalOverTime && this.BytesToRead < 5); //接收缓冲区的字符数
int readBuf = this.BytesToRead; if (readBuf < 5)
{
continue;
}
else
{
//接收数据
read = new byte[readBuf];
this.Read(read, 0, read.Length); //根据给定数组,计算CRC值
int CrcValue = CalculateCrc(read); //比较CRC值
if ((read[read.Length - 2] == (CrcValue & 0xFF)) && (read[read.Length - 1] == ((CrcValue >> 8) & 0xFF)))
{
//数值接收正确
isSuccess[i] = true; continue;
}
else
{
//CRC校验错误
continue;
}
}
}
}
return isSuccess; }
catch (Exception ex)
{
throw new Exception(ex.Message);
}
finally
{
this.DiscardInBuffer();
this.DiscardOutBuffer(); this.Close();
this.Dispose();
}
}
希望相关的.net开发者&&初学者家入(但是一定要经常的在线)
我要保证在线人数
能让大家的问题及时得到解决!
欢迎加入 共同进步!
还有好像我2台电脑用串口连接后,这个程序是正常工作的。
你可以建立一个Timer。
在Tick里面把所有的数据都读出来,然后分析数据显示。
没必要一个数据一个数据的收,那样很麻烦。
因为数据是持续发送 所以也没清空缓冲区