以下是我用vb 2008 express寫RS232 接收程式,現在是可以讀到別的地方傳過
來的資料,但是讀取的是Unicode,我要將他轉成二進制,以數字顯示,卻一直都失敗,
我試過一些方法,一樣會在txtReceive顯示"~",想請問大家是否有其他方法嗎? 謝
謝 (紅色部分是編碼跟顯示部分)
- Imports System.IO.Ports
- Imports System.Text
- Public Class Form1
- Dim RS232 As SerialPort
- Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
- For Each sp As String In SerialPort.GetPortNames()
- cmbCOM.Items.Add(sp)
- Next
- cmbCOM.Sorted = True
- cmbCOM.SelectedIndex = 0
- btnSend.Enabled = False
- End Sub
- Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
- Dim mBaudRate As Integer
- Dim mParity As IO.Ports.Parity
- Dim mDataBit As Integer
- Dim mStopbit As IO.Ports.StopBits
- Dim mPortName As String
- mPortName = cmbCOM.SelectedItem.ToString
- mBaudRate = 9600
- mParity = Parity.None
- mDataBit = 8
- mStopbit = StopBits.One
- RS232 = New IO.Ports.SerialPort(mPortName, mBaudRate, mParity, mDataBit, mStopbit)
- RS232.Encoding = Encoding.Unicode
- If Not RS232.IsOpen Then
- RS232.Open()
- btnSend.Enabled = True
- Timer1.Interval = 100
- Timer1.Enabled = True
- Else
- MsgBox("通訊埠已被開啟", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
- End
- End If
- End Sub
- Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
- If RS232 Is Nothing OrElse Not RS232.IsOpen Then
- MsgBox("通訊埠尚未開啟", MsgBoxStyle.Critical Or MsgBoxStyle.OkCancel)
- Else
- btnSend.Enabled = False
- Timer1.Enabled = False
- RS232.Close()
- End If
- End Sub
- Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
- Dim InString As String
- Dim HE As String
- InString = ""
- Try
- RS232.ReadTimeout = 1000
- InString = RS232.ReadExisting()
- HE = Val("&H RS232.ReadExisting()")
- If InString.Length = 0 Then
- Exit Sub
- Else
- txtReceive.Text += Hex(HE)
- End If
- Catch ex As Exception
- MessageBox.Show("讀取錯誤:" + ex.ToString, "錯誤通知", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
- End Try
- End Sub
- Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
- RS232.Write(txtSend.Text)
- End Sub
- Private Sub btnEnd_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnEnd.Click
- If Not RS232 Is Nothing Then
- If RS232.IsOpen Then RS232.Close()
- End If
- End
- End Sub
- End Class
複製代碼 ... |