創建C#串口通信程序詳解在.NET平臺下創建C#串口通信程序,.NET 2.0提供了串口通信的功能,其命名空間是System.IO.Ports。這個新的框架不但可以訪問計算機上的串口,還可以和串口設備進行通信。我們將使用標準的RS 232 C 在PC間通信。它工作在全雙工模式下,而且我們不打算使用任何的握手或流控制器,而是使用無modem連接。創建C#串口通信程序的具體實現是如何的呢?讓我們開始吧:
創建C#串口通信程序之命名空間
System.IO.Ports命名空間中最重用的是SerialPort 類。
創建C#串口通信程序之創建SerialPort 對象
通過創建SerialPort 對象,我們可以在程序中控制串口通信的全過程。
我們將要用到的SerialPort 類的方法:
ReadLine():從輸入緩沖區讀一新行的值,如果沒有,會返回NULL
WriteLine(string):寫入輸出緩沖
Open():打開一個新的串口連接
Close():關閉
- //createaSerialPortobject
- SerialPortsp=newSerialPort();
默認情況下,DataBits 值是8,StopBits 是1,通信端口是COM1。這些都可以在下面的屬性中重新設置:
BaudRate:串口的波特率
StopBits:每個字節的停止位數量
ReadTimeout:當讀操作沒有完成時的停止時間。單位,毫秒
還有不少其它公共屬性,自己查閱MSDN。
創建C#串口通信程序之串口的硬件知識
在數據傳輸的時候,每個字節的數據通過單個的電纜線傳輸。包包括開始位,數據,結束為。一旦
開始位傳出,后面就會傳數據,可能是5,6,7或8位,就看你的設定了。發送和接收必須設定同樣
的波特率和數據位數。
創建C#串口通信程序之無貓模式
沒有Modem模式的電纜只是簡單地交叉傳送和接收線。同樣DTR & DSR, 和 RTS & CTS也需要交叉。
這里,我們三條線。互連2和3(一段的2pin連接3pin),連接兩端的5pin。
創建C#串口通信程序示例程序
如果想使用默認屬性,按“Save Status”按鈕,如果想改變屬性按“PRoperty”。設定好之后,可以通信了。
主窗口的代碼
- #regionUsingdirectives
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.ComponentModel;
- usingSystem.Data;
- usingSystem.Drawing;
- usingSystem.Windows.Forms;
- usingSystem.IO.Ports;
- #endregion
- namespaceSerialexpample
- {
- partialclassForm1:Form
- {
- //createinstanceofpropertypage
- //propertypageisusedtosetvaluesforstopbitsand
- //baudrate
- PropertyPagepp=newPropertyPage();
- //createanSerialPortobject
- SerialPortsp=newSerialPort();
- publicForm1()
- {
- InitializeComponent();
- }
- privatevoidpropertyButton_Click(objectsender,EventArgse)
- {
- //showpropertydialog
- pp.ShowDialog();
- propertyButton.Hide();
- }
- privatevoidsendButton_Click(objectsender,EventArgse)
- {
- try
- {
- //writelinetoserialport
- sp.WriteLine(textBox.Text);
- //clearthetextbox
- textBox.Text="";
- }
- catch(System.Exceptionex)
- {
- baudRatelLabel.Text=ex.Message;
- }
- }
- privatevoidReadButton_Click(
- objectsender,EventArgse)
- {
- try
- {
- //clearthetextbox
- textBox.Text="";
- //readserialportanddisplayedthedataintextbox
- textBox.Text=sp.ReadLine();
- }
- catch(System.Exceptionex)
- {
- baudRatelLabel.Text=ex.Message;
- }
- }
- privatevoidForm1_Load(objectsender,EventArgse)
- {
- }
- privatevoidForm1_FormClosing(
- objectsender,FormClosingEventArgse)
- {
- MessageBox.Show("DouwanttoClosetheApp");
- sp.Close();
- }
- privatevoidstartCommButton_Click(
- objectsender,EventArgse)
- {
- startCommButton.Hide();
- sendButton.Show();
- readButton.Show();
- textBox.Show();
- }
- //whenwewanttosavethestatus(value)
- privatevoidsaveStatusButton_Click_1(
- objectsender,EventArgse)
- {
- //displayvalues
- //ifnopropertyissetthedefaultvalues
- if(pp.bRate==""&&pp.sBits=="")
- {
- dataBitLabel.Text="BaudRate="+
- sp.BaudRate.ToString();
- readTimeOutLabel.Text="StopBits="+
- sp.StopBits.ToString();
- }
- else
- {
- dataBitLabel.Text="BaudRate="+
- pp.bRate;
- readTimeOutLabel.Text="StopBits="+pp.sBits;
- } //創建C#串口通信程序
- parityLabel.Text="DataBits="+
- sp.DataBits.ToString();
- stopBitLabel.Text="Parity="+
- sp.Parity.ToString();
- readTimeOutLabel.Text="ReadTimeout="+
- sp.ReadTimeout.ToString();
- if(propertyButton.Visible==true)
- propertyButton.Hide();
- saveStatusButton.Hide();
- startCommButton.Show();
- try
- {
- //openserialport
- sp.Open();
- //setreadtimeoutto500ms
- sp.ReadTimeout=500;
- }
- catch(System.Exceptionex)
- {
- baudRatelLabel.Text=ex.Message;
- }
- }
- }
- }
創建C#串口通信程序之屬性設置對話框代碼:
- #regionUsingdirectives
- usingSystem;
- usingSystem.Collections.Generic;
- usingSystem.ComponentModel;
- usingSystem.Data;
- usingSystem.Drawing;
- usingSystem.Text;
- usingSystem.Windows.Forms;
- #endregion
- namespaceSerialexpample
- {
- partialclassPropertyPage:Form
- {
- //variablesforstoringvaluesofbaudrateandstopbits
- privatestringbaudR="";
- privatestringstopB="";
- //propertyforsettingandgettingbaudrateandstopbits
- publicstringbRate
- {
- get
- {
- returnbaudR;
- }
- set
- {
- baudR=value;
- }
- }
- publicstringsBits
- {
- get
- {
- returnstopB;
- }
- set
- {
- stopB=value;
- }
- }
- publicPropertyPage()
- {
- InitializeComponent();
- }
- privatevoidcancelButton_Click(