- 9
- 0
- 约4.27千字
- 约 7页
- 2017-06-08 发布于重庆
- 举报
通讯埠专题实验
通訊埠專題實驗
迴路測試:p3-23 LoopTest
迴路測試-使用SerialPort控制項:p3-33 LoopTest2
數位輸出:p3-37 comDO
數位輸入:p3-47 PinEvent-Timer
自動偵測與事件處理:p3-57 AutoReceive
自動傳送資料:p3-68 AutoSendReceive
事件處理與執行緒:p3-75 comEvent-First
使用DataReceived事件:p3-85 comEvent
委派處理:p3-90 comEvent2
使用PinChanged事件測試數位輸入:p3-90 comDI
計時器與DoEvents()事件進階應用:P3-101 TimerDoevent
建立執行緒:p3-106 AutoReceive-Thread
程式設計重點解說
在類別模組上方引入通訊埠物件參考
Imports System.IO.Ports
Imports System.Text
在類別模組內第一行宣告通訊埠物件
Dim RS232 As SerialPort
在Form_Load事件內替ComPort下拉組合方塊加入選項資料
For Each sp As String In SerialPort.GetPortNames
cmbCOM.Items.Add(sp)
Next
cmbCOM.Sorted = True 排序
cmbCOM.SelectedIndex = 0 第一個是預設選項
開啟通訊埠程式碼
Dim mBaudRate As Integer
Dim mParity As Parity
Dim mDataBit As Integer
Dim mStopbit As StopBits
Dim mPortName As String
mPortName = cmbCOM.SelectedItem.ToString 欲開啟的通訊埠
mBaudRate = 9600 通訊速度
mParity = Parity.None 同位位元檢查設定
mDataBit = 8 資料位元設定值
mStopbit = StopBits.One 停止位元設定值
建立一個通訊埠物件
RS232 = New SerialPort(mPortName, mBaudRate, mParity, mDataBit, mStopbit)
RS232.Encoding = Encoding.Unicode 設定編碼方式為Unicode,以便能顯示中文
If Not RS232.IsOpen Then 尚未開啟
RS232.Open() 開啟通訊埠
btnSend.Enabled = True 致能傳送按鈕
btnReceive.Enabled = True
Else
MsgBox(~~通訊埠開啟錯誤(通訊埠已被開啟)~~, MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
End
End If
傳送資料
RS232.Write(txtSend.Text)
接收資料
Dim InString As String
InString =
Try
RS232.ReadTimeout = 1000
InString = RS232.ReadExisting()
If InString Is Nothing Then
Exit Sub
Else
txtReceive.Text = InString
End If
Catch ex As Exception
MessageBox.Show(讀取錯誤: + ex.ToString, 錯誤通知, MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
End Try
關閉通訊埠程式碼
If RS232 Is Nothing OrElse Not RS232.IsOpen Then 尚未開啟
MsgBox(~~通訊埠尚未開啟~~, MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
Else
RS232.Close()
btnSend.Enabled = False
btnReceive.Enabled = False
End If
結束程式
If Not RS232 Is Nothing Then 判斷是否已建立通訊物件
If RS232.IsOpen Then RS232.Close() 若已開啟
原创力文档

文档评论(0)