using System; 
 using System.Collections.Generic; 
 using System.ComponentModel; 
 using System.Data; 
 using System.Drawing; 
 using System.Text; 
 using System.Windows.Forms; 
 using System.IO.Ports; 
 using System.Threading; 
 namespace TestSerialPort 
 { 
     public partial class frmTESTSerialPort : Form 
     { 
         public frmTESTSerialPort() 
         { 
             InitializeComponent(); 
             Control.CheckForIllegalCrossThreadCalls = false; 
         } 
         private Button button1; 
         private TextBox txtSend; 
         private TextBox txtReceive; 
         private Label label1; 
         private Label label2; 
         /// <summary> 
         /// 必需的设计器变量。 
         /// </summary> 
         private System.ComponentModel.IContainer components = null; 
         /// <summary> 
         /// 清理所有正在使用的资源。 
         /// </summary> 
         /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param> 
         protected override void Dispose(bool disposing) 
         { 
             if (disposing && (components != null)) 
             { 
                 components.Dispose(); 
             } 
             base.Dispose(disposing); 
         } 
         #region Windows 窗体设计器生成的代码 
         /// <summary> 
         /// 设计器支持所需的方法 - 不要 
         /// 使用代码编辑器修改此方法的内容。 
         /// </summary> 
         private void InitializeComponent() 
         { 
             this.button1 = new System.Windows.Forms.Button(); 
             this.txtSend = new System.Windows.Forms.TextBox(); 
             this.txtReceive = new System.Windows.Forms.TextBox(); 
             this.label1 = new System.Windows.Forms.Label(); 
             this.label2 = new System.Windows.Forms.Label(); 
             this.SuspendLayout(); 
             // 
             // button1 
             // 
             this.button1.Location = new System.Drawing.Point(440, 379); 
             this.button1.Name = "button1"; 
             this.button1.Size = new System.Drawing.Size(75, 23); 
             this.button1.TabIndex = 0; 
             this.button1.Text = "发送"; 
             this.button1.UseVisualStyleBackColor = true; 
             this.button1.Click += new System.EventHandler(this.button1_Click); 
             // 
             // txtSend 
             // 
             this.txtSend.Location = new System.Drawing.Point(59, 12); 
             this.txtSend.Multiline = true; 
             this.txtSend.Name = "txtSend"; 
             this.txtSend.Size = new System.Drawing.Size(456, 164); 
             this.txtSend.TabIndex = 2; 
             // 
             // txtReceive 
             // 
             this.txtReceive.Location = new System.Drawing.Point(59, 200); 
             this.txtReceive.Multiline = true; 
             this.txtReceive.Name = "txtReceive"; 
             this.txtReceive.Size = new System.Drawing.Size(456, 164); 
             this.txtReceive.TabIndex = 2; 
             // 
             // label1 
             // 
             this.label1.Location = new System.Drawing.Point(13, 15); 
             this.label1.Name = "label1"; 
             this.label1.Size = new System.Drawing.Size(41, 12); 
             this.label1.TabIndex = 0; 
             this.label1.Text = "发送"; 
             // 
             // label2 
             // 
             this.label2.Location = new System.Drawing.Point(13, 213); 
             this.label2.Name = "label2"; 
             this.label2.Size = new System.Drawing.Size(41, 12); 
             this.label2.TabIndex = 0; 
             this.label2.Text = "接收"; 
             // 
             // frmTESTSerialPort 
             // 
             this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); 
             this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
             this.ClientSize = new System.Drawing.Size(546, 434); 
             this.Controls.Add(this.label2); 
             this.Controls.Add(this.label1); 
             this.Controls.Add(this.txtReceive); 
             this.Controls.Add(this.txtSend); 
             this.Controls.Add(this.button1); 
             this.Name = "frmTESTSerialPort"; 
             this.Text = "串口试验"; 
             this.ResumeLayout(false); 
             this.PerformLayout(); 
         } 
         #endregion 
 private void button1_Click(object sender, EventArgs e) 
         { 
             //实例化串口对象(默认:COMM1,9600,e,8,1)             
             SerialPort serialPort1 = new SerialPort(); 
             //更改参数 
             serialPort1.PortName = "COM1"; 
             serialPort1.BaudRate = 19200; 
             serialPort1.Parity = Parity.Odd; 
             serialPort1.StopBits = StopBits.Two; 
             //上述步骤可以用在实例化时调用SerialPort类的重载构造函数 
             //SerialPort serialPort = new SerialPort("COM1", 19200, Parity.Odd, StopBits.Two); 
             //打开串口(打开串口后不能修改端口名,波特率等参数,修改参数要在串口关闭后修改) 
             serialPort1.Open(); 
             //发送数据 
             SendStringData(serialPort1); 
             //也可用字节的形式发送数据 
             //SendBytesData(serialPort1); 
              
             //开启接收数据线程 
             ReceiveData(serialPort1); 
              
         } 
          
         //发送字符串数据 
         private void SendStringData(SerialPort serialPort) 
         { 
             serialPort.Write(txtSend.Text); 
         } 
         /// <summary> 
         /// 开启接收数据线程 
         /// </summary> 
         private void ReceiveData(SerialPort serialPort) 
         { 
             //同步阻塞接收数据线程 
             Thread threadReceive=new Thread(new ParameterizedThreadStart(SynReceiveData)); 
             threadReceive.Start(serialPort); 
              
              //也可用异步接收数据线程 
             //Thread threadReceiveSub = new Thread(new ParameterizedThreadStart(AsyReceiveData)); 
             //threadReceiveSub.Start(serialPort); 
              
         } 
         //发送二进制数据 
         private void SendBytesData(SerialPort serialPort) 
         { 
             byte[] bytesSend=System.Text.Encoding.Default.GetBytes(txtSend.Text ); 
             serialPort.Write(bytesSend, 0, bytesSend.Length); 
         } 
         //同步阻塞读取 
         private void SynReceiveData(object serialPortobj) 
         { 
             SerialPort serialPort = (SerialPort)serialPortobj; 
             System.Threading.Thread.Sleep(0); 
             serialPort.ReadTimeout = 1000; 
             try 
             { 
                 //阻塞到读取数据或超时(这里为2秒) 
                 byte firstByte=Convert.ToByte(serialPort.ReadByte()); 
                 int bytesRead=serialPort.BytesToRead ;                
                 byte[] bytesData=new byte[bytesRead+1]; 
                 bytesData[0] = firstByte; 
                 for (int i = 1; i <=bytesRead; i++) 
                     bytesData = Convert.ToByte( serialPort.ReadByte()); 
                 txtReceive.Text = System.Text.Encoding.Default.GetString(bytesData); 
             } 
             catch(Exception e) 
             { 
                 MessageBox.Show(e.Message); 
                 //处理超时错误 
             } 
              
             serialPort.Close(); 
         } 
         //异步读取 
         private void AsyReceiveData(object serialPortobj) 
         { 
             SerialPort serialPort = (SerialPort)serialPortobj; 
             System.Threading.Thread.Sleep(500); 
             try 
             { 
                  txtReceive.Text =   serialPort.ReadExisting(); 
             } 
             catch (Exception e) 
             { 
                 MessageBox.Show(e.Message); 
                 //处理错误 
             } 
             serialPort.Close(); 
         } 
     } 
  
     static class Program 
     { 
         /// <summary> 
         /// 应用程序的主入口点。 
         /// </summary> 
         [STAThread] 
         static void Main() 
         { 
             Application.EnableVisualStyles(); 
             Application.SetCompatibleTextRenderingDefault(false); 
             Application.Run(new frmTESTSerialPort()); 
         } 
     } 
 }

SerialPort的更多相关文章

  1. SerialPort 串口开发

    private SerialPort sPort = new SerialPort(); //串行端口资源 /// <summary> /// 函数功能:打开串口/关闭串口 /// < ...

  2. C#SerialPort如何读取串口数据并显示在TextBox上

    SerialPort中串口数据的读取与写入有较大的不同.由于串口不知道数据何时到达,因此有两种方法可以实现串口数据的读取.一.线程实时读串口:二.事件触发方式实现. 由于线程实时读串口的效率不是十分高 ...

  3. [注意]SerialPort操作PCI-1621D多串口卡,出现异常"参数不正确"

    开发LED大屏显示.40-20mA模拟量输出的时候,经常要与串口打交道.但是Windows自带的SerialPort串口操作组件貌似兼容性 不是太好,或是SerialPort本身有BUG,在操作PCI ...

  4. 对比SerialCommunication和微软的SerialPort,向SerialPort看齐

    SerialCommunication是我综合网上看到的代码稍作修改而成的串口通信类,而SerialPort则是C#的System类库的IO目录Ports子目录下的串口通信类.SerialCommun ...

  5. 如何通过SerialPort读取和写入设备COM端口数据

    SerialPort类用于控制串行端口文件资源.提供同步 I/O 和事件驱动的 I/O.对管脚和中断状态的访问以及对串行驱动程序属性的访问.另外,SerialPort的功能可以包装在内部 Stream ...

  6. 使用SerialPort 读取外置GPS信息和使用GeoCoordinateWatcher获取内置gps的信息

    简介最近工作中需要读取gps设备的信息,平板本身有内置的gps设备,但是精度不够,就又添加了一个外置的gps.对于外置的gps,我们主要通过SerialPort类来获得串口的信息,然后对接收到的内容进 ...

  7. 记一次串口通信调试,慎用SerialPort.Close

    做项目是遇到了串口通信,真是遇到了一个大坑,不知道是微软的坑还是我的坑. 让我慢慢道来完整的经历. 项目中以前是vb 写的,是vb与vb 之间进行串口通信,现在改成C#和之前的vb程序进行串口通信. ...

  8. C# 通过SerialPort简单调用串口

    问题 最近比较经常使用串口进行发送以及传输数据,但是笔者在刚开始接触SerialPort类时,对于Write之后去Read数据的时候,由于设备上面还没有返回数据,读取到的只能是空值.然而,再进行下一次 ...

  9. [转]微软SerialPort秘籍[SerialPort为什么死锁程序的分析]

    既然是秘籍,显然是写一些大家不常找到的,MSDN里遗漏提示大家注意的东西. 用过.net 2.0中,自带SerialPort的人,大多都遇到过.莫名其妙的执行Close的时候会死掉的问题.而Wince ...

  10. 串行通讯之.NET SerialPort异步写数据

    目录 第1章说明    2 1 为什么需要异步写数据?    2 2 异步写数据的代码    2 3 源代码    4 第1章说明 1 为什么需要异步写数据? 如下图所示,以波特率300打开一个串口. ...

随机推荐

  1. Timer和TimerTask

    目录结构: Timer和TimerTask 一个Timer调度的例子 如何终止Timer线程 关于cancle方式终止线程 反复执行一个任务 schedule VS. scheduleAtFixedR ...

  2. java面试题集3

    一.选择题 1.下面程序的运行结果是 int i=0; while(true){ if(i++>10)  break; System.out.println(i); }1-11 2.下面程序的运 ...

  3. H5页面之iphone6的适配

    兼容iphone各版本机型最佳的方式就是自适应. 1.viewport 简单粗暴的方式: 1 <meta name="viewport" content="widt ...

  4. 【特殊的图+DP】【11月校赛】大家一起玩游戏

    大家一起玩游戏 Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other) Total Submi ...

  5. 初入 Spring.net

    IOC:Inversion Of Control 控制翻转:就是创建对象的权利由开发人员自己控制,转换到了由容器来控制 我用的是winform里的一个按键来触发的 首先要引入两个Spring.net的 ...

  6. 消除多余的row

    tableviewName.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];

  7. Sql Server trace flags

    Tace flag number Description -T1205 每次deadlock算法运行时,都收集相关的信息 -T1204 当deadlock算法发现死锁时才收集相关信息 -T3604 把 ...

  8. SqlHelper 简单版

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.D ...

  9. 基于vue2.0的一个分页组件

    分页组件在项目中经常要用到之前一直都是在网上找些jq的控件来用(逃..),最近几个项目用上vue了项目又刚好需要一个分页的功能.于是百度发现几篇文章介绍的实在方式有点复杂, 没耐心看自己动手造轮子写了 ...

  10. S​Q​L​ ​S​e​r​v​e​r​中​​的​P​W​D​E​N​C​R​Y​P​T​与​P​W​D​C​O​M​P​A​R​E​函​数

    前幾天有個客戶的網站出問題(不是我們開發的),請我們幫他看,主要的問題是他們的網站會員在進行查詢密碼時,會員收到信的時候在密碼的欄位竟然會出現 System.Binary[] 字樣.而我進去資料庫中查 ...