串口通讯代码

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.IO.Ports;//导入串口的命名空间namespace_01_SerialPort{publicpartialclassForm1:Form{publicdelegatevoidshowReceiveDelegate(stringtext);//当采用响应模式,应申明一个委托,实现不同线程的控件实验SerialPortcom=newSerialPort(COM2,9600,Parity.None,8,StopBits.One);//初始化构造函数publicForm1(){InitializeComponent();}///summary///窗体加载////summary///paramname=sender/param///paramname=e/paramprivatevoidForm1_Load(objectsender,EventArgse){cmbPort.SelectedIndex=0;cmbBaudRate.SelectedIndex=0;cmbDataBits.SelectedIndex=0;cmbStopBits.SelectedIndex=0;cmbParity.SelectedIndex=0;}///summary///串口打开与关闭////summary///paramname=sender/param///paramname=e/paramprivatevoidbtnOpen_Click(objectsender,EventArgse){if(btnOpen.Text==打开串口){try{if(!com.IsOpen){com.PortName=cmbPort.Text;com.BaudRate=int.Parse(cmbBaudRate.Text);com.DataBits=int.Parse(cmbDataBits.Text);switch(cmbStopBits.SelectedIndex){case0:com.StopBits=StopBits.One;break;case1:com.StopBits=StopBits.Two;break;case2:com.StopBits=StopBits.OnePointFive;break;case3:com.StopBits=StopBits.None;break;}switch(cmbParity.SelectedIndex){case0:com.Parity=Parity.None;break;case1:com.Parity=Parity.Odd;break;case2:com.Parity=Parity.Even;break;}com.Open();//打开串口}btnOpen.Text=关闭串口;txtStatus.Text=串口已打开!;btnSend.Enabled=true;if(rbAck.Checked)btnReceive.Enabled=true;//应答模式,接收按钮有效}catch{txtStatus.Text=串口打开错误或串口不存在!;}}else//关闭串口try{if(com.IsOpen)com.Close();//关闭串口btnOpen.Text=打开串口;txtStatus.Text=串口已关闭!;btnSend.Enabled=false;if(rbAck.Checked)btnReceive.Enabled=false;//应答模式,接收按钮有效}catch{txtStatus.Text=串口关闭错误或串口不存在!;}}///summary///串口发送数据////summary///paramname=sender/param///paramname=e/paramprivatevoidbtnSend_Click(objectsender,EventArgse){try{byte[]data=null;if(chkSendHex.Checked)data=getBytesFromString(txtSend.Text);elsedata=Encoding.Default.GetBytes(txtSend.Text);com.Write(data,0,data.Length);}catch(Exceptionerr){txtStatus.Text=err.ToString();}}///summary///串口接收数据,应答模式时////summary///paramname=sender/param///paramname=e/paramprivatevoidbtnReceive_Click(objectsender,EventArgse){try{//应答模式intcount=com.BytesToRead;byte[]readBuffer=newbyte[count];com.Read(readBuffer,0,count);if(chkRecHex.Checked)txtReceive.Text=getStringFromBytes(readBuffer);//转十六进制elsetxtReceive.Text=Encoding.Default.GetString(readBuffer);//字母、数字、汉字转换为字符串}catch(Exceptionerr){txtStatus.Text=err.ToString();}}///summary///数据接收模式变化时,设置串口的数据接收侦听事件////summary///paramname=sender/param///paramname=e/paramprivatevoidrbResponse_CheckedChanged(objectsender,EventArgse){try{btnReceive.Enabled=rbAck.Checked;if(rbResponse.Checked)com.DataReceived+=newSerialDataReceivedEventHandler(com_DataReceived);//加载接收事件elsecom.DataReceived-=newSerialDataReceivedEventHandler(com_DataReceived);//移除接收事件}catch(Exceptionerr){txtStatus.Text=err.ToString();}}///summary///响应模式时,串口接收数据事件////summary///paramname=sender/param///paramname=e/paramprivatevoidcom_DataReceived(objectsender,System.IO.Ports.SerialDataReceivedEventArgse){try{intcount=com.BytesToRead;byte[]readBuffer=newbyte[count];com.Read(readBuffer,0,count);stringstrReceive=;if(chkRecHex.Checked)strReceive=getStringFromBytes(readBuffer);//转十六进制elsestrReceive=Encoding.Default.GetString(readBuffer);//字母、数字、汉字转换为字符串this.Invoke(newshowReceiveDelegate(doShowReceive),strReceive);}catch(Exceptionerr){txtStatus.Text=err.ToString();}}///summary/////异步线程处理接受的字符,显示在接收的文本框中////summary///paramname=str/parampublicvoiddoShowReceive(stringstr){txtReceive.Text+=str;}///summary///以十六进制数据发送转换时,显示转换对应数据////summary///paramname=sender/param///paramname=e/paramprivatevoidchkSendHex_CheckedChanged(objectsender,EventArgse){try{if(chkSendHex.Checked)txtSend.Text=getStringFromBytes(Encoding.Default.GetBytes(txtSend.Text));elsetxtSend.Text=Encoding.Default.GetString(getBytesFromString(txtSend.Text));}catch{txtStatus.Text=数据转换出错,请输入正确的数据格式;}}///summary///以十六进制数据显示接收数据时,显示对应数据////summary///paramname=e/paramprivatevoidchkRecHex_CheckedChanged(objectsender,EventArgse){try{if(chkRecHex.Checked)txtReceive.Text=getStringFromBytes(Encoding.Default.GetBytes(txtReceive.Text));elsetxtReceive.Text=Encoding.Default.GetString(getBytesFromString(txtReceive.Text));}catch{txtStatus.Text=数据转换出错,请输入正确的数据格式;}}///summary///把十六进制格式的字符串转换成字节数组。////summary///paramname=pString要转换的十六进制格式的字符串/param///returns返回字节数组。/returnspublicstaticbyte[]getBytesFromString(stringpString){string[]str=pString.Split('');//把十六进制格式的字符串按空格转换为字符串数组。byte[]bytes=newbyte[str.Length];//定义字节数组并初始化,长度为字符串数组的长度。for(inti=0;istr.Length;i++)//遍历字符串数组,把每个字符串转换成字节类型赋值给每个字节变量。bytes[i]=Convert.ToByte(Convert.ToInt32(str[i],16));returnbytes;//返回字节数组。}///summary///把字节数组转换为十六进制格式的字符串。////summary///paramname=pByte要转换的字节数组。/param///returns返回十六进制格式的字符串。/returnspublicstaticstringgetStringFromBytes(byte[]pByte){stringstr=;//定义字符串类型临时变量。//遍历字节数组,把每个字节转换成十六进制字

1 / 6
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功