基于C#實現(xiàn)串口通信
本文實例為大家分享了C#實現(xiàn)串口通信的具體代碼,供大家參考,具體內容如下
1.基本概念

2.前端winForm布局如下(僅僅為了實現(xiàn)功能,布局略丑)

3.代碼實現(xiàn)如下
namespace SerialPortTest
? {
? ? ? public partial class Form1 : Form
? ? ? {
? ? ? ? ? SerialPort sp1 = new SerialPort();
? ? ? ? ? public Form1()
? ? ? ? ? {
? ? ? ? ? ? ? InitializeComponent();
? ? ? ? ? }
??
? ? ? ? ? private void Form1_Load(object sender, EventArgs e)
? ? ? ? ? {
?//分別對應前端的波特率、數(shù)字位、校驗位、停止位
? ? ? ? ? ? ? cbBaudRate.SelectedIndex = 0;
? ? ? ? ? ? ? cbDataBits.SelectedIndex = 0;
? ? ? ? ? ? ? cbCheck.SelectedIndex = 0;
? ? ? ? ? ? ? cbStop.SelectedIndex = 0;
??
? ? ? ? ? ? ? string[] strCom = SerialPort.GetPortNames();
? ? ? ? ? ? ? if (strCom == null)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("本機沒有串口!", "Error");
? ? ? ? ? ? ? ? ? return;
? ? ? ? ? ? ? }
? ? ? ? ? ? ? //GetPortNames()方法:獲取當前計算機的串行端口名的數(shù)組
? ? ? ? ? ? ? foreach (string com in System.IO.Ports.SerialPort.GetPortNames())
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? cbCom.Items.Add(com);
? ? ? ? ? ? ? }
??
? ? ? ? ? ? ? cbCom.SelectedIndex = 0;
? ? ? ? ? ? ? sp1.BaudRate = 9600;
? ? ? ? ? ? ? Control.CheckForIllegalCrossThreadCalls = false;
? ? ? ? ? ? ? sp1.DataReceived += Sp1_DataReceived;
? ? ? ? ? ? ? ? ? ? ? ? ? ?
? ? ? ? ? ? ? sp1.DtrEnable = true;//獲取或設置一個值,該值在串行通信過程中啟用數(shù)據終端就緒 (DTR) 信號。
? ? ? ? ? ? ? sp1.RtsEnable = true;//獲取或設置一個值,該值指示在串行通信中是否啟用請求發(fā)送 (RTS) 信號
? ? ? ? ? ? ? //設置數(shù)據讀取超時為1秒
? ? ? ? ? ? ? sp1.ReadTimeout = 1000;
??
? ? ? ? ? ? ? sp1.Close();
? ? ? ? ? }
??
? ? ? ? ? private void Sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
? ? ? ? ? {
? ? ? ? ? ? ? if (sp1.IsOpen) ? ? //判斷是否打開串口
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? //輸出當前時間
? ? ? ? ? ? ? ? ? DateTime dt = DateTime.Now;
? ? ? ? ? ? ? ? ? txtReceived.Text += dt.GetDateTimeFormats('f')[0].ToString() + "\r\n";
? ? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? Byte[] receivedData = new Byte[sp1.BytesToRead]; ? ? ? ?//創(chuàng)建接收字節(jié)數(shù)組
? ? ? ? ? ? ? ? ? ? ? sp1.Read(receivedData, 0, receivedData.Length); ? ? ? ? //讀取數(shù)據
? ? ? ? ? ? ? ? ? ? ? AddContent(new UTF8Encoding().GetString(receivedData));//用萬能的UTF8可以傳輸中文不會亂碼
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? ? ?catch (System.Exception ex)
? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? MessageBox.Show(ex.Message, "出錯提示!!!!!");
? ? ? ? ? ? ? ? ? ? ? txtSendStr.Text = "";
? ? ? ? ? ? ? ? ? }
? ? ? ? ? ? ? }
? ? ? ? ? ? ? else
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("請打開某個串口", "錯誤提示");
? ? ? ? ? ? ? }
? ? ? ? ? }
??
? ? ? ? ? //將接受到的內容顯示出來
? ? ? ? ? private void AddContent(string content)
? ? ? ? ? {
? ? ? ? ? ? ? this.BeginInvoke(new MethodInvoker(delegate
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? txtReceived.AppendText(content);
? ? ? ? ? ? ? ? ? txtReceived.AppendText("\r\n");
? ? ? ? ? ? ? ? ? //記錄收到的字符個數(shù)
? ? ? ? ? ? ? ? ? lblRevCount.Text = (int.Parse(lblRevCount.Text) + content.Length).ToString();
? ? ? ? ? ? ? }));
? ? ? ? ? }
??
? ? ? ? ? private void btnOpen_Click(object sender, EventArgs e)
? ? ? ? ? {
? ? ? ? ? ? ? //serialPort1.IsOpen
? ? ? ? ? ? ? if (!sp1.IsOpen)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? try
? ? ? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? ? ? //設置串口號
? ? ? ? ? ? ? ? ? ? ? string serialName = cbCom.SelectedItem.ToString();
? ? ? ? ? ? ? ? ? ? ? sp1.PortName = serialName;
??
? ? ? ? ? ? ? ? ? ? ? //設置各“串口設置”
? ? ? ? ? ? ? ? ? ? ? string strBaudRate = cbBaudRate.Text;
? ? ? ? ? ? ? ? ? ? ? string strDateBits = cbDataBits.Text;
? ? ? ? ? ? ? ? ? ? ? string strStopBits = cbStop.Text;
? ? ? ? ? ? ? ? ? ? ? Int32 iBaudRate = Convert.ToInt32(strBaudRate);
? ? ? ? ? ? ? ? ? ? ? Int32 iDateBits = Convert.ToInt32(strDateBits);
?
? ? ? ? ? ? ? ? ? ? ?sp1.BaudRate = iBaudRate; ? ? ? //波特率
? ? ? ? ? ? ? ? ? ? ?sp1.DataBits = iDateBits; ? ? ? //數(shù)據位
? ? ? ? ? ? ? ? ? ? ?switch (cbStop.Text) ? ? ? ? ? ?//停止位
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ?case "1":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.One;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "1.5":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.OnePointFive;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "2":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.StopBits = StopBits.Two;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?default:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:參數(shù)不正確!", "Error");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ? ? ?switch (cbCheck.Text) ? ? ? ? ? ? //校驗位
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ?case "無":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.None;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "奇校驗":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Odd;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?case "偶校驗":
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Parity = Parity.Even;
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ? ? ?default:
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:參數(shù)不正確!", "Error");
? ? ? ? ? ? ? ? ? ? ? ? ? ? ?break;
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? ? ? ? ?if (sp1.IsOpen == true)//如果打開狀態(tài),則先關閉一下
? ? ? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ? ? ?sp1.Close();
? ? ? ? ? ? ? ? ? ? ?}
?
? ? ? ? ? ? ? ? ? ? ?//設置必要控件不可用
? ? ? ? ? ? ? ? ? ? ?cbCom.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbDataBits.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbStop.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?cbCheck.Enabled = false;
? ? ? ? ? ? ? ? ? ? ?sp1.Open(); ? ? //打開串口
? ? ? ? ? ? ? ? ? ? ?btnOpen.Text = "關閉串口";
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ? ? ?catch (System.Exception ex)
? ? ? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ? ? ?MessageBox.Show("Error:" + ex.Message, "Error");
? ? ? ? ? ? ? ? ? ? ?return;
? ? ? ? ? ? ? ? ?}
? ? ? ? ? ? ?}
? ? ? ? ? ? ?else
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?//恢復控件功能
? ? ? ? ? ? ? ? ?//設置必要控件不可用
? ? ? ? ? ? ? ? ?cbCom.Enabled = true;
? ? ? ? ? ? ? ? ?cbBaudRate.Enabled = true;
? ? ? ? ? ? ? ? ?cbDataBits.Enabled = true;
? ? ? ? ? ? ? ? ?cbStop.Enabled = true;
? ? ? ? ? ? ? ? ?cbCheck.Enabled = true;
? ? ? ? ? ? ? ? ?sp1.Close(); ? ? ? ? ? ? ? ? ? ?//關閉串口
? ? ? ? ? ? ? ? ?btnOpen.Text = "打開串口";
? ? ? ? ? ? ?}
? ? ? ? ?}
?
? ? ? ? ?private void btnSend_Click(object sender, EventArgs e)
? ? ? ? ?{
? ? ? ? ? ? ?byte[] sendData = null;
? ? ? ? ? ? ?if (!sp1.IsOpen) //如果沒打開
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?MessageBox.Show("請先打開串口!", "Error");
? ? ? ? ? ? ? ? ?return;
? ? ? ? ? ? ?}
? ? ? ? ? ? ?String strSend = txtSendStr.Text;
? ? ? ? ? ? ?try
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?sendData = Encoding.UTF8.GetBytes(txtSendStr.Text.Trim());
? ? ? ? ? ? ? ? //sp1.WriteLine(txtSendStr.Text); ? ?//寫入數(shù)據
? ? ? ? ? ? ? ? ?sp1.Write(sendData, 0, sendData.Length);
? ? ? ? ? ? ? }
? ? ? ? ? ? ? catch (Exception ex)
? ? ? ? ? ? ? {
? ? ? ? ? ? ? ? ? MessageBox.Show("Error:" + ex.Message, "Error");
}
?
}
?
}
}4.測試運行結果如下
在自己同一臺電腦上測試,需要先用Configure Virtual Serial Port Driver建立兩個虛擬串口,如下

串口運行結果如下:

上述兩窗體通信時要選擇同一波特率,不然收發(fā)數(shù)據會失敗
關于C# serialport的一些說明:
SerialPort() :如果未指定,則此構造函數(shù)使用默認屬性值。 例如, DataBits 屬性默認值為 8, Parity 屬性默認為 None 枚舉值,
StopBits 屬性默認值為 1,默認端口名為 COM1。
public static string[] GetPortNames() :獲取當前計算機的串行端口名的數(shù)組
SerialPort.Read 方法 (Byte[], Int32, Int32) :從 SerialPort 輸入緩沖區(qū)讀取一些字節(jié)并將那些字節(jié)寫入字節(jié)數(shù)組中指定的偏移量處
SerialPort.ReadLine 方法 () :一直讀取到輸入緩沖區(qū)中的 NewLine 值
SerialPort.Write 方法 (Byte[], Int32, Int32) : 使用緩沖區(qū)中的數(shù)據將指定數(shù)量的字節(jié)寫入串行端口
SerialPort.WriteLine 方法 (String) : 將指定的字符串和 NewLine 值寫入輸出緩沖區(qū)。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

