C# 串口操作系列.docx
- 文档编号:4642579
- 上传时间:2022-12-07
- 格式:DOCX
- 页数:41
- 大小:108.02KB
C# 串口操作系列.docx
《C# 串口操作系列.docx》由会员分享,可在线阅读,更多相关《C# 串口操作系列.docx(41页珍藏版)》请在冰豆网上搜索。
C#串口操作系列
字符串转16进制字节数组
viewplaincopytoclipboardprint?
privatestaticbyte[]strToToHexByte(stringhexString)
{
hexString=hexString.Replace("","");
if((hexString.Length%2)!
=0)
hexString+="";
byte[]returnBytes=newbyte[hexString.Length/2];
for(inti=0;i returnBytes[i]=Convert.ToByte(hexString.Substring(i*2,2),16); returnreturnBytes; } privatestaticbyte[]strToToHexByte(stringhexString) { hexString=hexString.Replace("",""); if((hexString.Length%2)! =0) hexString+=""; byte[]returnBytes=newbyte[hexString.Length/2]; for(inti=0;i returnBytes[i]=Convert.ToByte(hexString.Substring(i*2,2),16); returnreturnBytes; } 字节数组转16进制字符串 viewplaincopytoclipboardprint? publicstaticstringbyteToHexStr(byte[]bytes) { stringreturnStr=""; if(bytes! =null) { for(inti=0;i { returnStr+=bytes[i].ToString("X2"); } } returnreturnStr; } publicstaticstringbyteToHexStr(byte[]bytes) { stringreturnStr=""; if(bytes! =null) { for(inti=0;i { returnStr+=bytes[i].ToString("X2"); } } returnreturnStr; } 从汉字转换到16进制 viewplaincopytoclipboardprint? publicstaticstringToHex(strings,stringcharset,boolfenge) { if((s.Length%2)! =0) { s+="";//空格 //thrownewArgumentException("sisnotvalidchinesestring! "); } System.Text.Encodingchs=System.Text.Encoding.GetEncoding(charset); byte[]bytes=chs.GetBytes(s); stringstr=""; for(inti=0;i { str+=string.Format("{0: X}",bytes[i]); if(fenge&&(i! =bytes.Length-1)) { str+=string.Format("{0}",","); } } returnstr.ToLower(); } publicstaticstringToHex(strings,stringcharset,boolfenge) { if((s.Length%2)! =0) { s+="";//空格 //thrownewArgumentException("sisnotvalidchinesestring! "); } System.Text.Encodingchs=System.Text.Encoding.GetEncoding(charset); byte[]bytes=chs.GetBytes(s); stringstr=""; for(inti=0;i { str+=string.Format("{0: X}",bytes[i]); if(fenge&&(i! =bytes.Length-1)) { str+=string.Format("{0}",","); } } returnstr.ToLower(); } 从16进制转换成汉字 viewplaincopytoclipboardprint? publicstaticstringUnHex(stringhex,stringcharset) { if(hex==null) thrownewArgumentNullException("hex"); hex=hex.Replace(",",""); hex=hex.Replace("\n",""); hex=hex.Replace("\\",""); hex=hex.Replace("",""); if(hex.Length%2! =0) { hex+="20";//空格 } //需要将hex转换成byte数组。 byte[]bytes=newbyte[hex.Length/2]; for(inti=0;i { try { //每两个字符是一个byte。 bytes[i]=byte.Parse(hex.Substring(i*2,2), System.Globalization.NumberStyles.HexNumber); } catch { //Rethrowanexceptionwithcustommessage. thrownewArgumentException("hexisnotavalidhexnumber! ","hex"); } } System.Text.Encodingchs=System.Text.Encoding.GetEncoding(charset); returnchs.GetString(bytes); } C#操作串口类实例 privatevoidForm1_Load(objectsender,EventArgse) { this.Text="DevAspComPortAPP"; cmbBaudRate.SelectedIndex=0; cmbDataBits.SelectedIndex=0; cmbParity.SelectedIndex=0; cmbPortName.SelectedIndex=0; cmbStopBits.SelectedIndex=0; } privatevoidport_DataReceived(objectsender,SerialDataReceivedEventArgse) { //Thismethodwillbecalledwhenthereisdatawaitingintheport'sbuffer //Determainwhichmode(stringorbinary)theuserisin //Readallthedatawaitinginthebuffer try { stringdata=""; data=comport.ReadLine();//.ReadExisting(); //Displaythetexttotheuserintheterminal paringdata(data); } catch(Exceptionex) { MessageBox.Show(ex.Message); } //label2.Invoke(newEventHandler(delegate{label2.Text=data;})); //Log(LogMsgType.Incoming,data); } privatevoidForm1_FormClosing(objectsender,FormClosingEventArgse) { try { //comport.DiscardOutBuffer(); //comport.DiscardInBuffer(); //comport.Dispose(); if(comport.IsOpen) { comport.ReadExisting(); comport.Close(); } } catch(Exceptionex) { MessageBox.Show(ex.Message); } } privatevoidbutton1_Click(objectsender,EventArgse) { //Iftheportisopen,closeit. try { if(button1.Text=="Start") { if(comport.IsOpen)comport.Close(); else { //Settheport'ssettings comport.BaudRate=int.Parse(cmbBaudRate.Text); comport.DataBits=int.Parse(cmbDataBits.Text); comport.StopBits=(StopBits)Enum.Parse(typeof(StopBits),cmbStopBits.Text); comport.Parity=(Parity)Enum.Parse(typeof(Parity),cmbParity.Text); comport.PortName=cmbPortName.Text; comport.ReadTimeout=100; comport.Open(); button1.Text="Stop"; } } else { if(comport.IsOpen) { comport.ReadExisting(); comport.Close(); } button1.Text="Start"; } } catch(Exceptionex) { MessageBox.Show(ex.Message); } } 使用SerialPort类的方法: 方法一: 首先要添加 usingSystem.IO; usingSystem.IO.Ports; 1...在类的内部定义SerialPortcom; 2...打开串口 com=newSerialPort(); com.BaudRate=115200; com.PortName="COM1"; com.DataBits=8; com.Open();//打开串口 3...发送数据 Byte[]TxData={1,2,3,4,5,6,7,8}; com.Write(TxData,0,8); 4...接收数据 4.1使用事件接收 .DataReceived+=newSystem.IO.Ports.SerialDataReceivedEventHandler (this.OnDataReceived); privatevoidOnDataReceived(objectsender,SerialDataReceivedEventArgse) 4.2使用线程接收 接收数据启动一个线程,使其接收。 在类的内部定义 Thread_readThread; bool_keepReading; 打开串口后启动线程 _keepReading=true; _readThread=newThread(ReadPort); _readThread.Start(); 线程函数 privatevoidReadPort() { while(_keepReading) { if(com.IsOpen) { byte[]readBuffer=newbyte[com.ReadBufferSize+1]; try { //Iftherearebytesavailableontheserialport, //Readreturnsupto"count"bytes,butwillnotblock(wait) //fortheremainingbytes.Iftherearenobytesavailable //ontheserialport,Readwillblockuntilatleastonebyte //isavailableontheport,upuntiltheReadTimeoutmilliseconds //haveelapsed,atwhichtimeaTimeoutExceptionwillbethrown. intcount=com.Read(readBuffer,0,com.ReadBufferSize); StringSerialIn=System.Text.Encoding.ASCII.GetString(readBuffer,0,count); if(count! =0) //byteToHexStr(readBuffer); ThreadFunction(byteToHexStr(readBuffer,count)); } catch(TimeoutException){} } else { TimeSpanwaitTime=newTimeSpan(0,0,0,0,50); Thread.Sleep(waitTime); } } } 方法二: 使用C#自带的SerialPor控件 1...在“工具箱”的“组件”中选择SerialPor控件添加。 2...设置串口并打开 serialPort1.PortName="COM1"; serialPort1.BaudRate=9600; serialPort1.Open(); 3...写入数据可以使用Write或者下面的函数 serialPort1.WriteLine(str); 4...添加数据接收的事件 privatevoidserialPort1_DataReceived(objectsender,SerialDataReceivedEventArgse) 使用中的一些常见问题 C#中SerialPort类中DataReceived事件GUI实时处理方法 MSDN: 从SerialPort对象接收数据时,将在辅助线程上引发DataReceived事件。 由于此事件在辅助线程而非主线程上引发,因此尝试修改主线程中的一些元素(如UI元素)时会引发线程异常。 如果有必要修改主Form或Control中的元素,必须使用Invoke回发更改请求,这将在正确的线程上执行.进而要想将辅助线程中所读到的数据显示到主线程的Form控件上时,只有通过Invoke方法来实现 下面是代码实例: privatevoidserialPort1_DataReceived(objectsender,SerialDataReceivedEventArgse) { intSDateTemp=this.serialPort1.ReadByte(); //读取串口中一个字节的数据 this.tB_ReceiveDate.Invoke( //在拥有此控件的基础窗口句柄的线程上执行委托Invoke(Delegate) //即在textBox_ReceiveDate控件的父窗口form中执行委托. newMethodInvoker( /*表示一个委托,该委托可执行托管代码中声明为void且不接受任何参数的任何方法。 在对控件的Invoke方法进行调用时或需要一个简单委托又不想自己定义时可以使用该委托。 */ delegate{ /*匿名方法,C#2.0的新功能,这是一种允许程序员将一段完整代码区块当成参数传递的程序代码编写技术,通过此种方法可以直接使用委托来设计事件响应程序以下就是你要在主线程上实现的功能但是有一点要注意,这里不适宜处理过多的方法,因为C#消息机制是消息流水线响应机制,如果这里在主线程上处理语句的时间过长会导致主UI线程阻塞,停止响应或响应不顺畅,这时你的主form界面会延迟或卡死*/ this.tB_ReceiveDate.AppendText(SDateTemp.ToString());//输出到主窗口文本控件 this.tB_ReceiveDate.Text+="";} ) ); } C#串口操作系列 C#串口操作系列 (1)--入门篇,一个标准的,简陋的串口例子。 我假设读者已经了解了c#的语法,本文是针对刚打算解除串口编程的朋友阅读的,作为串口编程的入门范例,也是我这个系列的基础。 我们的开发环境假定为vs2005(虽然我在用vs2010,但避免有些网友用2005,不支持lambda,避免不兼容,就用2005来做例子) 一个基本的串口程序,既然是个程序了。 我们就先从功能说起,包含 串口选择波特率选择打开关闭 接受数据显示发送数据输入发送数据数据量提示以及归零 好吧,有了这些功能,我们就先画出界面。 例如: 这里,波特率就定死几种好了。 直接界面上添加2400,4800,9600,19200,38400,57600,115200 comboPortName这里,为了我们的软件能通用所有电脑避免每次查询的效率损失,我们使用微软提供的枚举方式,代码如下: viewplaincopytoclipboardprint? string[]ports=SerialPort.GetPortNames(); Array.Sort(ports); comboPortName.Items.AddRange(ports); string[]ports=SerialPort.GetPortNames(); Array.Sort(ports); comboPortName.Items.AddRange(ports); 显然,我们需要定义一个SerialPort对象。 添加DataReceived事件响应收到数据,还有一个重点,我们需要记得设置NewLine属性哦。 好想有的版本不设置的时候,WriteLine和Write效果一样。 所以,我们需要初始化SerialPort对象,例如: viewplaincopytoclipboardprint? //初始化SerialPort对象 comm.NewLine="\r\n"; comm.RtsEnable=true;//根据实际情况吧。 //添加事件注册 comm.DataReceived+=comm_DataReceived; //初始化SerialPort对象 comm.NewLine="\r\n"; comm.RtsEnable=true;//根据实际情况吧。 //添加事件注册 comm.DataReceived+=comm_DataReceived; 初始化好串口,简单的编写打开,关闭方法,编写界面响应的是否自动换行,如何复位计数器,发送方法。 以及数据处理。 因为我已经写了完整注视,我就直接贴代码了。 usingSystem; usingSystem.Collections.Generic; usingSystem.ComponentModel; usingSystem.Data; usingSystem.Drawing; usingSystem.Linq; usingSystem.Text; usingSystem.Windows.Forms; usingSystem.IO.Ports; usingSystem.Text.RegularExpressions; namespaceSerialportSample { publicpartialclassSerialportSampleForm: Form { privateSerialPortcomm=newSerialPort(); privateStringBuilderbuilder=newStringBuilder(); //避免在事件处理方法中反复的创建,定义到外面。 privatelongreceived_count=0;//接收计数 privatelongsend_count=0;//发送计数 publicSerialportSampleForm() { InitializeComponent(); } //窗体初始化 privatevoidForm1_Load(objectsender,EventArgse)
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- C# 串口操作系列 串口 操作 系列
![提示](https://static.bdocx.com/images/bang_tan.gif)