這篇文章主要講解了“C#如何實現串口通信”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“C#如何實現串口通信”吧!
1.基本概念

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

3.代碼實現如下
namespace SerialPortTest
{
public partial class Form1 : Form
{
SerialPort sp1 = new SerialPort();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//分別對應前端的波特率、數字位、校驗位、停止位
cbBaudRate.SelectedIndex = 0;
cbDataBits.SelectedIndex = 0;
cbCheck.SelectedIndex = 0;
cbStop.SelectedIndex = 0;
string[] strCom = SerialPort.GetPortNames();
if (strCom == null)
{
MessageBox.Show("本機沒有串口!", "Error");
return;
}
//GetPortNames()方法:獲取當前計算機的串行端口名的數組
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;//獲取或設置一個值,該值在串行通信過程中啟用數據終端就緒 (DTR) 信號。
sp1.RtsEnable = true;//獲取或設置一個值,該值指示在串行通信中是否啟用請求發送 (RTS) 信號
//設置數據讀取超時為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]; //創建接收字節數組
sp1.Read(receivedData, 0, receivedData.Length); //讀取數據
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");
//記錄收到的字符個數
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; //數據位
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:參數不正確!", "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:參數不正確!", "Error");
break;
}
if (sp1.IsOpen == true)//如果打開狀態,則先關閉一下
{
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); //寫入數據
sp1.Write(sendData, 0, sendData.Length);
}
catch (Exception ex)
{
MessageBox.Show("Error:" + ex.Message, "Error");
}
}
}
}4.測試運行結果如下
在自己同一臺電腦上測試,需要先用Configure Virtual Serial Port Driver建立兩個虛擬串口,如下

串口運行結果如下:

上述兩窗體通信時要選擇同一波特率,不然收發數據會失敗
關于C# serialport的一些說明:
SerialPort() :如果未指定,則此構造函數使用默認屬性值。 例如, DataBits 屬性默認值為 8, Parity 屬性默認為 None 枚舉值,
StopBits 屬性默認值為 1,默認端口名為 COM1。
public static string[] GetPortNames() :獲取當前計算機的串行端口名的數組
SerialPort.Read 方法 (Byte[], Int32, Int32) :從 SerialPort 輸入緩沖區讀取一些字節并將那些字節寫入字節數組中指定的偏移量處
SerialPort.ReadLine 方法 () :一直讀取到輸入緩沖區中的 NewLine 值
SerialPort.Write 方法 (Byte[], Int32, Int32) : 使用緩沖區中的數據將指定數量的字節寫入串行端口
SerialPort.WriteLine 方法 (String) : 將指定的字符串和 NewLine 值寫入輸出緩沖區。
感謝各位的閱讀,以上就是“C#如何實現串口通信”的內容了,經過本文的學習后,相信大家對C#如何實現串口通信這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。