源代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace 串口通信
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
public int iPort = 1; //1,2,3,4
public int iRate = 9600; //1200,2400,4800,9600
public byte bSize = 8; //8 bits
public byte bParity = 0; // 0-4=no,odd,even,mark,space
public byte bStopBits = 1; // 0,1,2 = 1, 1.5, 2
public int iTimeout = 1000;
public myCom com = new myCom();
public byte[] recb;
public int nub = 0;
//打开串口
public bool openCom()
{
try {
if (com.Opened)
{
com.Close();
com.Open();
}
else
{
com.Open();
}
return true;
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//显示包信息
public string disPackage(byte[] reb)
{
string temp = "";
foreach (byte b in reb)
temp += b.ToString("X2") + " ";
return temp;
}
//去掉字符数组中的空格
public string delSpace(string input)
{
string output = "";
for(int i=0;i
{
if(input!=' ')
output += input;
}
return output;
}
//发送数据包
public void sendPackage(byte[] bb)
{
int sendNum = 0;
try
{
sendNum = com.Write(bb);
Thread.Sleep(50);
this.txtShow.AppendText("\r\n发送数据:"+disPackage(bb));
recb = com.Read(50);
this.txtShow.AppendText("\r\n接收到数据:" + disPackage(recb));
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
//提取发送的数据包
public byte[] sendDB()
{
string temp = delSpace(this.txtSend.Text.Trim());
byte[] strTemp = new byte[50];
int j = 0;
try
{
for (int i = 0; i < temp.Length; i = i + 2, j++)
strTemp[j] = Convert.ToByte(temp.Substring(i, 2), 16);
}catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
byte[] send = new byte[j];
Array.Copy(strTemp, send, j);
return send;
}
//点击发送按钮发送数据
private void button4_Click(object sender, EventArgs e)
{
if (this.txtSend.Text == "")
{
MessageBox.Show("发送数据为空!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (com.Opened)
{
byte[] temp = se