求vb.net 2008版 SerialPort组件命令
大家好!如题:求vb.net 2008版 SerialPort组件命令,包括读、写
com1的端口初始化和端口关闭!
简单精炼即可!谢谢!
[解决办法]
Private Sub FrmQuery_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed
If sp.IsOpen Then
sp.Close()
End If
End Sub
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SendData()
End Sub
Private Sub SendData()
Dim data(5) As Char
Dim str As String = Chr(&H10) + Chr(&H7B) + Chr(&H0) + Chr(&H7B) + Chr(&H16)
Try
sp.Write(str)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
''' <summary>
''' 同步委托
''' </summary>
''' <remarks></remarks>
Public Delegate Sub myDelegate()
''' <summary>
''' 接收数据
''' </summary>
''' <param name="sender"></param>
''' <param name="e"></param>
''' <remarks></remarks>
Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
Dim DB() As SByte
Dim LEN, N As Integer
Dim str As String = ""
' Thread.Sleep(100)
'触发-串口收到数据
txtDataReceived.Invoke(New myDelegate(AddressOf updateTextBox), New Object() {})
If sp.BytesToRead > 0 Then
End If
'If sp.BytesToRead > 0 Then
' ReDim DB(sp.BytesToRead)
'End If
'For M As Integer = 1 To sp.BytesToRead
' DB(M) = sp.ReadByte
' str = str + " " + Format(Hex(DB(M)), "00")
'Next
' TextBox1.Text = str
End Sub
Public Sub updateTextBox()
Static n As Integer
'显示更新串口收到的数据
With txtDataReceived
If Not rbRAsc.Checked Then '字符
.AppendText(sp.ReadExisting) '& vbCrLf)
Else '16进制
Dim iReceivedbytes As Integer, i As Integer
Dim strReceiveBytes As String
Dim bReadByte() As Byte
Dim strHex As String = ""
iReceivedbytes = sp.BytesToRead 'buffer中所有字节数
ReDim bReadByte(iReceivedbytes - 1)
If m_bStopDisp = False Then
sp.Read(bReadByte, 0, iReceivedbytes)
'.AppendText(bReadByte(0).ToString)
For i = 0 To iReceivedbytes - 1
strReceiveBytes = Hex(bReadByte(i))
strHex = strHex & IIf(LEN(strReceiveBytes) > 1, strReceiveBytes, "0" & strReceiveBytes) & " "
Next
n = n + 1
.AppendText(n & ":" & strHex & vbCrLf)
End If
End If
.ScrollToCaret()
End With
End Sub
Private Sub btnCom_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCom.Click
If btnCom.Text = "open" Then
sp.Open()
btnCom.Text = "close"
Else
sp.Close()
btnCom.Text = "open"
End If
End Sub
这里包括打开和关闭串口sp,发送和接受数据
[解决办法]
下载:VB.NET 串口工程