欢迎来到天天文库
浏览记录
ID:11396979
大小:16.30 KB
页数:4页
时间:2018-07-11
《简单的c#串口通信》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.IO.Ports;usingSystem.IO;namespaceWindowsApplication6{publicpartialclassFormfilerec:Form{publicFormfilerec(){InitializeComponent();}i
2、ntsentnumber=0;privateSerialPortcomm=newSerialPort();//建立一个对象publicdelegatevoidHandleInterfaceUpdataDelegate(stringtext);privateHandleInterfaceUpdataDelegateinterfaceUpdataHandle;privatevoidForm1_Load(objectsender,EventArgse){}//发送按钮privatevoidbuttonsent_Click(objectsender,EventArgse){byte[]dat
3、a=Encoding.Unicode.GetBytes(textBoxsent.Text);stringstr=Convert.ToBase64String(data);comm.WriteLine(str);sentnumber=sentnumber+textBoxsent.Text.Length;//记录发送数this.textBox1.Text=Convert.ToString(sentnumber);if(str.Length!=0){//MessageBox.Show("数据发送成功!","系统提示");textBoxsent.Text=null;//清空}elseMess
4、ageBox.Show("发送为空。","系统提示");}//打开关闭串口按钮privatevoidbuttonOpenClose_Click(objectsender,EventArgse){//根据当前串口对象,来判断操作if(comm.IsOpen){comm.Close();//打开时点击,则关闭串口}else{//关闭时点击,则设置好端口,波特率等后打开if(comboBoxComNum.Text.Length!=0)comm.PortName=comboBoxComNum.Text;elseMessageBox.Show("请选择串口号!","系统提示");if(comb
5、oBoxBaudRate.Text.Length==0)MessageBox.Show("请选择波特率!","系统提示");elsecomm.BaudRate=int.Parse(comboBoxBaudRate.Text);if(comboBoxByteSize.Text.Length==0)MessageBox.Show("请选择数据位!","系统提示");elsecomm.DataBits=int.Parse(comboBoxByteSize.Text);if(comboBoxStopBits.Text=="1")comm.StopBits=StopBits.One;elsei
6、f(comboBoxStopBits.Text=="2")comm.StopBits=StopBits.Two;elseMessageBox.Show("请选择停止位!","系统提示");if(comboBoxByteSize.Text.Length!=0&&comboBoxBaudRate.Text.Length!=0&&comboBoxComNum.Text.Length!=0)comm.Open();//打开串口}//设置按钮的状态buttonOpenClose.Text=comm.IsOpen?"关闭":"打开";buttonsent.Enabled=comm.IsOpen;
7、}//串口监听publicvoidcomm_DataReceived(objectsender,System.IO.Ports.SerialDataReceivedEventArgse){byte[]readBuffer=Convert.FromBase64String(comm.ReadLine());this.Invoke(interfaceUpdataHandle,newstring[]{Encoding.Unicode.GetString(read
此文档下载收益归作者所有