串行端口开发的数据交互方式
- 摘要:引用程序集usingSystem.IO.Ports;字段定义//实例化串口类对象privateSerialPortcomm=newSerialPort();//实例化String类型的临时变量privateStringBuilderbuilder=newStringBuilder();//接收数据stringstrData=null;定义串口对象并设置参数privatevoidCreateSerialPortService(){comm.NewLine="\r\n";comm
- 标签:数据 方式 开发
using System.IO.Ports;
//实例化串口类对象
private SerialPort comm = new SerialPort();
//实例化String类型的临时变量
private StringBuilder builder = new StringBuilder();
//接收数据
string strData = null;
private void CreateSerialPortService() { comm.NewLine = "\r\n"; comm.RtsEnable = true; comm.DtrEnable = true; comm.PortName = "PortName"; //端口名,例如COM3 comm.BaudRate = "BaudRate"; //波特率,例如9600 comm.DataBits = "DataBits"; //数据位,例如8 comm.StopBits = StopBits.One; //停止位,例如StopBits。One(1位停止位) comm.Parity = Parity.None; //奇偶校验,例如Parity。None(无奇偶校验) //添加事件注册 comm.DataReceived += comm_DataReceived; //接收串口数据触发事件 }
void comm_DataReceived(object sender, SerialDataReceivedEventArgs e) { //先记录下来,避免某种原因,人为的原因,操作几次之间时间长,缓存不一致 int n = comm.BytesToRead; byte[] buf = new byte[n]; //声明一个临时数组存储当前来的串口数据 comm.Read(buf, 0, n); //读取缓冲数据 builder = new StringBuilder(); //清除字符串构造器的内容 //直接按ASCII规则转换成字符串 builder.Append(Encoding.ASCII.GetString(buf)); //追加的形式添加到文本框末端,并滚动到最后。 strData = builder.ToString();}
private void OpenOrCloseSerialPort() { //根据当前串口对象,来判断操作 if (comm.IsOpen) { //打开时点击,则关闭串口 comm.Close(); } else { //关闭时点击,则打开串口 comm.Open(); } }
private void Send(string text) { comm.Write(text); }