用的Microsoft Visual Studio 2010,是關於串口調試助手接收到的數據換行的問題,
在調試的時候都正常,是在每句結尾插入換行符,但是實際運行就變成隔幾個字符就出現一個換行,一條數據分了好幾行,這是為什麼呢?
能幫我看看是哪裡的問題麼?代碼如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
// 關閉標志,表示串口正在關閉
private bool closing = false;
//監聽標志, 用於安全關閉串口
private bool listening = false;
//累計發送字節
private long sendCount = 0;
//累計接收字節
private long receiveCount = 0;
//每次接收到的數據
string data;
//總的接收到的數據
string sa = "";
int b;
int d;
public Form1()
{
InitializeComponent();
}
//關閉串口按鈕事件
private void button1_Click(object sender, EventArgs e)
{
serialPort1.Close();
Close();
}
//串口初始化
private void Form1_Load(object sender, EventArgs e)
{
//設置默認屬性
if (comboBox_portName.Text == "")
comboBox_portName.Text = "COM1";
//查詢電腦上的串口並顯示在控件裡
foreach (string s in SerialPort.GetPortNames())
{
comboBox_portName.Items.Add(s);
}
//初始化combox2
comboBox_rate.Items.Add("300");
comboBox_rate.Items.Add("600");
comboBox_rate.Items.Add("1200");
comboBox_rate.Items.Add("2400");
comboBox_rate.Items.Add("4800");
comboBox_rate.Items.Add("9600");
comboBox_rate.Items.Add("19200");
comboBox_rate.Items.Add("38400");
comboBox_rate.Items.Add("76800");
comboBox_rate.Items.Add("115200");
comboBox_rate.SelectedIndex = 5;
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}
//打開串口
private void OpenSerialPort()
{
if (serialPort1.IsOpen)
{
return;
}
try
{
//根據comboBox設定串口名和波特率打開串口
serialPort1.PortName = comboBox_portName.Text;
serialPort1.BaudRate = int.Parse(comboBox_rate.Text);
serialPort1.Open();
if (serialPort1.IsOpen) //串口打開之後
{
button_openClosePort.Text = "關閉串口";
Label_mainMessage.ForeColor = Color.Green;
Label_mainMessage.Text = serialPort1.PortName + "已打開";
}
}
catch //異常狀態
{
Label_mainMessage.ForeColor = Color.Red;
Label_mainMessage.Text = "串口打開失敗!";
}
}
//關閉串口
private void CloseSerialPort()
{
if (!serialPort1.IsOpen)
{
return;
}
try
{
closing = true;
while (listening)
Application.DoEvents();
serialPort1.Close();
closing = false;
if (!serialPort1.IsOpen) //串口關閉之後
{
button_openClosePort.Text = "打開串口";
Label_mainMessage.ForeColor = Color.Green;
Label_mainMessage.Text = serialPort1.PortName + "已關閉";
}
}
catch //異常狀態
{
Label_mainMessage.ForeColor = Color.Red;
Label_mainMessage.Text = "串口關閉失敗!";
}
}
bool IsBr = false;
//顯示接收數據並進行相應的格式轉換
private void DisplayText(object sender, EventArgs e)
{
string a; //定義a存放每次接收到的數據
a = data;
StringBuilder buildHexPlay = new StringBuilder();
if (a.Length == 0) //窗口為空,不需要轉換
return;
if (check_hexPlay.Checked) //將字符轉換為HEX格式顯示
{
char[] bufString = new char[a.Length];
bufString = a.ToArray();
foreach (char c in bufString)
{
if (c == '\n')
buildHexPlay.Append("0");
buildHexPlay.Append(Convert.ToString(Convert.ToByte(c), 16) + " ");
}
a = buildHexPlay.ToString().ToUpper();
sa += a; //用sa存放2次一共接收到的數據
textBox_receive.Text = sa;
}
else //將HEX轉為字符顯示
{
textBox_receive.Text = textBox_receive.Text + data;
//string[] bufString = new string[textBox_receive.Text.Length];
//char[] split = { ' ', '\n', '\r' }; //將空格,回車符過濾,BUF:可能存在
//bufString = textBox_receive.Text.Trim().Split(split);
//foreach (string ss in bufString)
//{
// if (ss != "") //由於有回車符"\r\n"存在,所以得到的SS可能為""
// buildHexPlay.Append(Convert.ToChar(Convert.ToByte(ss, 16)));
//}
//textBox_receive.Text = textBox_receive.Text + data;
}
Label_receiveCount.Text = "接收字節:" + d; //顯示記數
}
private void button2_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen) //判斷串口是否打開
{
Label_mainMessage.ForeColor = Color.Red;
Label_mainMessage.Text = "串口未打開!";
return;
}
else
{
StringBuilder buildSend = new StringBuilder();
int count = 0;
//if (checkBox_hexSend.Checked) //發送16進制 這裡都需要16進制發送,所以不需要判斷
{
List<byte> bufferSend = new List<byte>();
// buildSend.Clear();
string sendSting =textBox_sendString.Text.Trim(); //刪去前導和後置空格符
string s = "";
while (sendSting.Length > 1) //奇數個16進制數據最後一個被拋棄
{
s = sendSting.Substring(0, 2);
buildSend.Append(s + " ");
bufferSend.Add(Convert.ToByte(s, 16)); //將字符s 如“1A” 轉化為字節31,送入字節列表BufferSend
sendSting = sendSting.Remove(0, 2);
sendSting = sendSting.Trim(); //刪去前導空格符
}
//textBox_sendString.Text = buildSend.ToString().ToUpper(); //格式化顯示發送的數據
serialPort1.Write(bufferSend.ToArray(), 0, bufferSend.ToArray().Length); //發送數據
//計算發送字節數
count = bufferSend.Count;
sendCount += count;
Label_sendCount.Text = "發送字節:" + sendCount.ToString(); //顯示記數
}
//else //asc編碼直接發送,發送字符
//{
// if (checkBox_sendNewLine.Checked) //發送新行
// {
// serialPort1.WriteLine(textBox_sendString.Text);
// count = textBox_sendString.Text.Length + 2;
// }
// else
// {
// serialPort1.Write(textBox_sendString.Text);
//count = textBox_sendString.Text.Length;
// }
//}
//sendCount += count;
//Label_sendCount.Text = sendCount.ToString();
}
}
//接收事件
void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (textBox_sendString.Text == "D1 FF" || textBox_sendString.Text == "D3 FF" || textBox_sendString.Text == "d1 ff" || textBox_sendString.Text == "d3 ff")
{
Byte[] receivedData = new Byte[serialPort1.BytesToRead]; //創建接收字節數組
serialPort1.Read(receivedData, 0, receivedData.Length); //讀取數據
//serialPort1.DiscardInBuffer(); //清空SerialPort控件的Buffer
string strRcv = null;
for (int i = 0; i < receivedData.Length; i++) //窗體顯示
{
strRcv += receivedData[i].ToString("X2") + " "; //16進制顯示
}
data = strRcv;
b = receivedData.Length;
d += b;
data = strRcv + "\r\n";
this.Invoke(new EventHandler(DisplayText));
}
else
{
data = serialPort1.ReadExisting(); //將接收到的數據傳給data
b = data.Length;
d += b;
data += "\r\n";
this.Invoke(new EventHandler(DisplayText));
}
}
//HEX顯示按鈕的格式轉換,與顯示接收事件中的一樣
private void check_hexPlay_CheckedChanged(object sender, EventArgs e)
{
StringBuilder buildHexPlay = new StringBuilder();
if (textBox_receive.Text.Length == 0) //窗口為空,不需要轉換
return;
if (check_hexPlay.Checked) //將字符轉換為HEX格式顯示
{
char[] bufString = new char[textBox_receive.Text.Length];
bufString = textBox_receive.Text.ToArray();
foreach (char c in bufString)
{
if(c == '\n')
buildHexPlay.Append("0");
buildHexPlay.Append(Convert.ToString(Convert.ToByte(c), 16) + " ");
}
textBox_receive.Text = buildHexPlay.ToString().ToUpper();
}
else //將HEX轉為字符顯示
{
string[] bufString = new string[textBox_receive.Text.Length];
char[] split = { ' ', '\n', '\r' }; //將空格,回車符過濾,BUF:可能存在
bufString = textBox_receive.Text.Trim().Split(split);
foreach (string ss in bufString)
{
if (ss != "") //由於有回車符"\r\n"存在,所以得到的SS可能為""
buildHexPlay.Append(Convert.ToChar(Convert.ToByte(ss, 16)));
}
textBox_receive.Text = buildHexPlay.ToString();
}
}
//打開/關閉串口按鈕事件
private void button_openClosePort_Click(object sender, EventArgs e)
{
if (button_openClosePort.Text == "打開串口")
OpenSerialPort();
else
CloseSerialPort();
}
//清除按鈕事件
private void buttonclear_Click(object sender, EventArgs e)
{
textBox_receive.Clear();
d = 0;
receiveCount = sendCount = 0; //清空計數器
Label_receiveCount.Text = "接收字節:0";
Label_sendCount.Text = "發送字節:0"; //清空記數顯示
}
}
}