现在的位置: 首页 > 综合 > 正文

C# 串口操作系列(1) — 入门篇,一个标准的,简陋的串口例子

2013年10月11日 ⁄ 综合 ⁄ 共 1624字 ⁄ 字号 评论关闭

来源:http://blog.csdn.net/wuyazhe/article/details/5598945

我假设读者已经了解了c#的语法,本文是针对刚打算解除串口编程的朋友阅读的,作为串口编程的入门范例,也是我这个系列的基础。

我们的开发环境假定为vs2005(虽然我在用vs2010,但避免有些网友用2005,不支持lambda,避免不兼容,就用2005来做例子)

 

一个基本的串口程序,既然是个程序了。我们就先从功能说起,包含

串口选择

波特率选择

打开

关闭

接受数据显示

发送数据输入

发送数据

数据量提示以及归零

好吧,有了这些功能,我们就先画出界面。例如:

 

这里,波特率就定死几种好了。直接界面上添加2400,4800,9600,19200,38400,57600,115200

comboPortName这里,为了我们的软件能通用所有电脑避免每次查询的效率损失,我们使用微软提供的枚举方式,代码如下:

 

[c-sharp] view
plain
copy

  1. string[] ports = SerialPort.GetPortNames();  
  2. Array.Sort(ports);  
  3. comboPortName.Items.AddRange(ports);  

 

显然,我们需要定义一个SerialPort对象。添加DataReceived事件响应收到数据,还有一个重点,我们需要记得设置NewLine属性哦。好想有的版本不设置的时候,WriteLine和Write效果一样。

 

所以,我们需要初始化SerialPort对象,例如:

[c-sharp] view
plain
copy

  1. //初始化SerialPort对象  
  2. comm.NewLine = "/r/n";  
  3. comm.RtsEnable = true;//根据实际情况吧。  
  4. //添加事件注册  
  5. comm.DataReceived += comm_DataReceived;  

 

 初始化好串口,简单的编写打开,关闭方法,编写界面响应的是否自动换行,如何复位计数器,发送方法。以及数据处理。因为我已经写了完整注视,我就直接贴代码了。

 

 

 

[c-sharp] view
plain
copy

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Windows.Forms;  
  9. using System.IO.Ports;  
  10. using System.Text.RegularExpressions;  
  11. namespace SerialportSample  
  12. {  
  13.     public partial class SerialportSampleForm : Form  
  14.     {  
  15.         private SerialPort comm = new SerialPort();  
  16.         private StringBuilder builder = new StringBuilder();//避免在事件处理方法中反复的创建,定义到外面。  
  17.         private long received_count = 0;//接收计数  
  18.         private long send_count = 0;//发送计数  
  19.         public SerialportSampleForm()  
  20.         {  
  21.             InitializeComponent();  
  22.         }  
  23.         //窗体初始化  
  24.         private void

抱歉!评论已关闭.