Private Sub SendButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SendButton.Click '發送
Dim a As Integer
Try
If Me.RadioButton3.Checked = True Then
Me.SerialPort1.Write(Me.TextBox1.Text)
a = Me.TextBox1.TextLength
SCount.Text = (a + CULng(SCount.Text))
Else
Dim SendConvert As String
SendConvert = ConvertHexChr(TextBox1.Text) '去空格
Dim BytSendDec As String
Dim Temp(0) As Byte
Dim i As Integer
Dim longth As Integer
longth = Len(SendConvert)
a = longth / 2
SCount.Text = (a + CULng(SCount.Text))
For i = 1 To longth Step 2
BytSendDec = Mid(SendConvert, i, 2)
Temp(0) = "&H" & BytSendDec
SerialPort1.Write(Temp, 0, 1)
Next
End If
If SCount.Text = "2147483647" Then
SCount.Text = 0
End If
Catch ex As Exception
MsgBox("發送失敗")
End Try
End Sub
Public Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived '接收
Dim a As Integer, i As Integer
a = SerialPort1.BytesToRead 'buffer中所有位元組數
ReDim ss(a - 1)
SerialPort1.Read(ss, 0, a)
SerialPort1.DiscardInBuffer()
If RadioButton1.Checked = True Then '字符顯示
For i = 0 To a - 1
TextBox2.AppendText(Chr(ss(i)))
Next
TextBox2.AppendText(Chr(32))
Else
For i = 0 To a - 1
If Len(Hex(ss(i))) = 1 Then
TextBox2.AppendText("0" & Hex(ss(i))) '16進制顯示
Else
TextBox2.AppendText(Hex(ss(i)))
End If
TextBox2.AppendText(Chr(32))
Next
End If
'計數
RCount.Text = (CStr(a + CULng(RCount.Text)))
If RCount.Text = "2147483647" Then
RCount.Text = 0
End If
End Sub
uj5u.com熱心網友回復:
發送的漢字全部是“?”uj5u.com熱心網友回復:
對于漢字,需要轉換才行,你采用Binary方式通信,把接收來的資料存在Byte型別的陣列中,然后再使用StrConv轉換即可。例如下面:
Option Explicit
Dim bytHanZi() As Byte
Dim intP As Integer
Private Sub Command1_Click()
bytHanZi = StrConv(Text1.Text, vbFromUnicode)
Text2.Text = ""
For intP = LBound(bytHanZi) To UBound(bytHanZi)
Text2.Text = Text2.Text & Right("00" & Hex(bytHanZi(intP)), 2)
Next intP
End Sub
Private Sub Command2_Click()
Text1.Text = StrConv(bytHanZi, vbUnicode)
End Sub
Private Sub Form_Load()
Text1.Text = "汗顏"
Text2.Text = ""
End Sub
Command2_Click中的代碼就是將位元組陣列中的內容轉換為漢字。
uj5u.com熱心網友回復:
已經會搞了,我設計室的高手改的,牛uj5u.com熱心網友回復:
有代碼嗎?串口接收到了資料,我一直顯示不出漢字來uj5u.com熱心網友回復:
同問,我接收到的漢字也是問號,想這個是怎么改的啊uj5u.com熱心網友回復:
接收也收到 Binary 陣列中,再 StrConv 成字串。轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/131245.html
標籤:控件
