上一篇讲的是Com通信的基本知识,这一篇讲一下Com开发实例
首先,找一个com头,有公母之分,现在一般都是Usb转Com的,短接一下Com头的2(接收pin)/3(发送pin),然后就可以进行测试了
在短接的时候注意一下别短接错了,使用winform做出如下的界面
1.定义一个SerialPort
private SerialPort ComDevice=new SerialPort();
2.Load初始化及接收数据的方法
private void Form_Load(object sender,EventArgs e)
{
//获取主机所有的COM口
cmbCom.Items.AddRange(SerialPort.GetPortNames());
if(cmbCom.Items.Count>0)
{
cmbCom.SelectedIndex=0;
}
cmbBaudRate.SelectedIndex=5;
cmbDataBits.SelectedIndex=0;
cmbCheck.SelectedIndex=0;
cmbStopBits.SelectedIndex=0;
//给DataReceived事件注册数据接收方法
ComDevice.DataReceived+=new SerialDataReceivedEventHandler(Com_DataReceived);
}
//接收数据
private void Com_DataReceived(object sender,SerialDataReceivedEventArgs e)
{
byte[] ReDatas=new byte[ComDevice.BytesToRead];
//读取数据
ComDevice.Read(ReDatas,0,ReDatas.Length);
//输出数据
AddData(ReDatas);
}
//根据选择的格式进行转换
private void AddData(byte[] reDatas)
{
if(rbtnHexReceive.Checked)
{
StringBuilder sb=new StringBuilder();
for(int i=0;i<reDatas.Length;i++)
{
sb.AppendFormat("{0:x2}"+" ",reDatas[i]);
}
AddContent(sb.ToString().ToUpper());
}
else if(rbtnAscReceive.Checked)
{
AddContent(new ASCIIEncoding().GetString(reDatas));
}
else if(rbtnUTFReceive.Checked)
{
AddContent(new UTF8Encoding().GetString(reDatas));
}
else if(rbtnUnicodeReceive.Checked)
{
AddContent(new UnicodeEncoding().GetString(reDatas));
}
txtReceiveCount.Invoke(new MethodInvoker(delegate
{
txtReceiveCount.Text=(int.Parse(txtReceiveCount.Text)+reDatas.Length).ToString();
}));
}
//委托执行控件信息
privte void AddContent(string content)
{
this.Invoke(new MethodInvoker(delegate
{
txtReceiveData.AppendText(content);
}));
}
3.打开Com口
private void btnOpenCom_Click(object sender,Eventargs e)
{
if(cmbCom.Items.Count<1)
{
MessageBox.Show("没有发现串口");
return;
}
if(ComDevice.IsOpen==false)
{
ComDevice.PortName=cmbCom.SelectedItem.ToString();
ComDevice.BaudRate=Convert.ToInt32(cmbBaudRate.SelectedItem.ToString());
ComDevice.Parity=(Parity)Convert.ToInt32(cmbCheck.SelectedIndex.ToString());
ComDevice.DataBits=Convert.ToInt32(cmbDataBits.SelectedItem.ToString());
ComDevice.StopBits=(StopBits)Convert.ToInt32(cmbStopBits.SelectedItem.ToString());
try
{
ComDevice.Open();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"error");
}
}
else
{
try
{
ComDevice.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message,"error");
}
}
}
4.发送数据
//串口发送数据
private bool SendData(byte[] data)
{
try
{
if(ComDevice.IsOpen)
{
ComDevice.Write(data,0,data.Length);
return true;
}
else
{
MessageBox.Show("串口未打开");
return false;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
//点击发送数据的动作
private void btnSend_Click(object sender,EventArgs e)
{
byte[] sendData=null;
if(rbtnHexSend.Checked)
{
sendData=strtoHexByte(txtSendData.Text.Trim());
}
else if(rbtnAscSend.Checked)
{
sendData=Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
}
else if(rbtnUTFSend.Checked)
{
sendData=Encoding.UTF8.GetBytes(txtSendData.Text.Trim());
}
else if(rbtnUnicodeSend.Checked)
{
sendData=Encoding.Unicode.GetBytes(txtSendData.Text.Trim());
}
else
{
sendData=Encoding.ASCII.GetBytes(txtSendData.Text.Trim());
}
//发送数据
if(this.SendData(sendData))
{
txtSendCount.Invoke(new MethodInvoker(delegate
{
txtSendCount.Text=(int.Parse(txtSendCount.Text)+txtSendData.Text.Length).ToString();
}));
}
else
{
;
}
}
//字符串转换为16进制的数组
private byte[] strtoHexByte(string hexString)
{
hexString=hexString.Replace(" ","");
if(hexString.Length%2!=0)
{
hexString+=" ";
}
byte[] returnBytes=new Byte[hexString.Length/2];
for(int i=0;i<returnBytes.Length;i++)
{
returnBytes[i]=Convert.ToByte(hexString.Substring(i*2,2).Replace(" ",""),16);
}
return returnBytes;
}
5.清空的动作
private void btnClearReceiveArea_Click(object sender,EventArgs e)
{
txtReceiveData.Clear();
}
private void btnClearSendArea_Click(object sender,EventArgs e)
{
txtSendData.CLear();
}