转自:http://blog.csdn.net/wuyazhe/article/details/5598945
我假设读者已经了解了c#的语法,本文是针对刚打算解除串口编程的朋友阅读的,作为串口编程的入门范例,也是我这个系列的基础。
我们的开发环境假定为vs2005(虽然我在用vs2010,但避免有些网友用2005,不支持lambda,避免不兼容,就用2005来做例子)
一个基本的串口程序,既然是个程序了。我们就先从功能说起,包含
串口选择
波特率选择
打开
关闭
接受数据显示
发送数据输入
发送数据
数据量提示以及归零
好吧,有了这些功能,我们就先画出界面。例如:
这里,波特率就定死几种好了。直接界面上添加2400,4800,9600,19200,38400,57600,115200
comboPortName这里,为了我们的软件能通用所有电脑避免每次查询的效率损失,我们使用微软提供的枚举方式,代码如下:
- string[] ports = SerialPort.GetPortNames();
- Array.Sort(ports);
- comboPortName.Items.AddRange(ports);
显然,我们需要定义一个SerialPort对象。添加DataReceived事件响应收到数据,还有一个重点,我们需要记得设置NewLine属性哦。好想有的版本不设置的时候,WriteLine和Write效果一样。
所以,我们需要初始化SerialPort对象,例如:
-
- comm.NewLine = "/r/n";
- comm.RtsEnable = true;
-
- comm.DataReceived += comm_DataReceived;
初始化好串口,简单的编写打开,关闭方法,编写界面响应的是否自动换行,如何复位计数器,发送方法。以及数据处理。因为我已经写了完整注视,我就直接贴代码了。
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Linq;
- using System.Text;
- using System.Windows.Forms;
- using System.IO.Ports;
- using System.Text.RegularExpressions;
- namespace SerialportSample
- {
- public partial class SerialportSampleForm : Form
- {
- private SerialPort comm = new SerialPort();
- private StringBuilder builder = new StringBuilder();
- private long received_count = 0;
- private long send_count = 0;
- public SerialportSampleForm()
- {
- InitializeComponent();
- }
-
- private void Form1_Load(object sender, EventArgs e)
- {
-
- string[] ports = SerialPort.GetPortNames();
- Array.Sort(ports);
- comboPortName.Items.AddRange(ports);
- comboPortName.SelectedIndex = comboPortName.Items.Count > 0 ? 0 : -1;
- comboBaudrate.SelectedIndex = comboBaudrate.Items.IndexOf("9600");
-
- comm.NewLine = "/r/n";
- comm.RtsEnable = true;
-
- comm.DataReceived += comm_DataReceived;
- }
- void comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
- {
- int n = comm.BytesToRead;
- byte[] buf = new byte[n];
- received_count += n;
- comm.Read(buf, 0, n);
- builder.Clear();
-
- this.Invoke((EventHandler)(delegate
- {
-
- if (checkBoxHexView.Checked)
- {
-
- foreach (byte b in buf)
- {
- builder.Append(b.ToString("X2") + " ");
- }
- }
- else
- {
-
- builder.Append(Encoding.ASCII.GetString(buf));
- }
-
- this.txGet.AppendText(builder.ToString());
-
- labelGetCount.Text = "Get:" + received_count.ToString();
- }));
- }
- private void buttonOpenClose_Click(object sender, EventArgs e)
- {
-
- if (comm.IsOpen)
- {
-
- comm.Close();
- }
- else
- {
-
- comm.PortName = comboPortName.Text;
- comm.BaudRate = int.Parse(comboBaudrate.Text);
- try
- {
- comm.Open();
- }
- catch(Exception ex)
- {
-
- comm = new SerialPort();
-
- MessageBox.Show(ex.Message);
- }
- }
-
- buttonOpenClose.Text = comm.IsOpen ? "Close" : "Open";
- buttonSend.Enabled = comm.IsOpen;
- }
-
- private void checkBoxNewlineGet_CheckedChanged(object sender, EventArgs e)
- {
- txGet.WordWrap = checkBoxNewlineGet.Checked;
- }
- private void buttonSend_Click(object sender, EventArgs e)
- {
-
- int n = 0;
-
- if (checkBoxHexSend.Checked)
- {
-
- MatchCollection mc = Regex.Matches(txSend.Text, @"(?i)[/da-f]{2}");
- List<byte> buf = new List<byte>();
-
- foreach (Match m in mc)
- {
- buf.Add(byte.Parse(m.Value));
- }
-
- comm.Write(buf.ToArray(), 0, buf.Count);
-
- n = buf.Count;
- }
- else
- {
-
- if (checkBoxNewlineSend.Checked)
- {
- comm.WriteLine(txSend.Text);
- n = txSend.Text.Length + 2;
- }
- else
- {
- comm.Write(txSend.Text);
- n = txSend.Text.Length;
- }
- }
- send_count += n;
- labelSendCount.Text = "Send:" + send_count.ToString();
- }
- private void buttonReset_Click(object sender, EventArgs e)
- {
-
- send_count = received_count = 0;
- labelGetCount.Text = "Get:0";
- labelSendCount.Text = "Send:0";
- }
- }
- }
至此,一个标准的串口调试助手就完成了。留下一个思考题,如果接收数据后,更新界面的时候,尚未操作完成,此时并发了关闭串口的操作。程序会如何呢?敬请阅读《C# 串口操作系列(2) -- 如何避免关闭串口偶尔软件死锁》。
VS2010项目范例下载
VS2008项目范例下载
//append by wuyazhe @2011-5-26
上面有一点疏漏,源自第一篇,结果到这里还是没修改,源码中有一行,需要修改一下。
//发送按钮中
buf.Add(byte.Parse(m.Value));
要修改为
buf.Add(byte.Parse(m.Value,System.Globalization.NumberStyles.HexNumber));