我假設(shè)讀者已經(jīng)了解了c#的語法,本文是針對剛打算解除串口編程的朋友閱讀的,作為串口編程的入門范例,,也是我這個系列的基礎(chǔ),。
我們的開發(fā)環(huán)境假定為vs2005(雖然我在用vs2010,但避免有些網(wǎng)友用2005,,不支持lambda,,避免不兼容,就用2005來做例子)
一個基本的串口程序,,既然是個程序了,。我們就先從功能說起,包含
串口選擇
波特率選擇
打開
關(guān)閉
接受數(shù)據(jù)顯示
發(fā)送數(shù)據(jù)輸入
發(fā)送數(shù)據(jù)
數(shù)據(jù)量提示以及歸零
好吧,,有了這些功能,,我們就先畫出界面。例如:
這里,,波特率就定死幾種好了,。直接界面上添加2400,4800,9600,19200,38400,57600,115200
comboPortName這里,為了我們的軟件能通用所有電腦避免每次查詢的效率損失,,我們使用微軟提供的枚舉方式,,代碼如下:
- string[] ports = SerialPort.GetPortNames();
- Array.Sort(ports);
- comboPortName.Items.AddRange(ports);
顯然,我們需要定義一個SerialPort對象,。添加DataReceived事件響應(yīng)收到數(shù)據(jù),,還有一個重點,我們需要記得設(shè)置NewLine屬性哦,。好想有的版本不設(shè)置的時候,,WriteLine和Write效果一樣,。
所以,我們需要初始化SerialPort對象,,例如:
-
- comm.NewLine = "/r/n";
- comm.RtsEnable = true;
-
- comm.DataReceived += comm_DataReceived;
初始化好串口,簡單的編寫打開,,關(guān)閉方法,,編寫界面響應(yīng)的是否自動換行,如何復(fù)位計數(shù)器,,發(fā)送方法,。以及數(shù)據(jù)處理。因為我已經(jīng)寫了完整注視,,我就直接貼代碼了,。
- 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";
- }
- }
- }
至此,,一個標(biāo)準(zhǔn)的串口調(diào)試助手就完成了,。留下一個思考題,,如果接收數(shù)據(jù)后,更新界面的時候,,尚未操作完成,,此時并發(fā)了關(guān)閉串口的操作。程序會如何呢,?敬請閱讀《C# 串口操作系列(2) -- 如何避免關(guān)閉串口偶爾軟件死鎖》,。
VS2010項目范例下載
VS2008項目范例下載
//append by wuyazhe @2011-5-26
上面有一點疏漏,源自第一篇,,結(jié)果到這里還是沒修改,,源碼中有一行,需要修改一下,。
//發(fā)送按鈕中
buf.Add(byte.Parse(m.Value));
要修改為
buf.Add(byte.Parse(m.Value,System.Globalization.NumberStyles.HexNumber));