SeialPo发送与接收16进制数据讲解
SerialPort发送与接收16进制数据程序
上位机和单片机通信用16进制比较多,下面是16进制通信的例子,数据发送用Write,数据接收用ReadByte。
Imports System.IO.Ports '使用SerialPort所引用的命名空间
Public Class Form1
Dim fx() As Byte '待发送数据数组
Dim Rc() As Byte '接收数据数组
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text="打开串口" Then
SerialPort1.PortName="COM1"
SerialPort1.Open() '串口打开与关闭
Button1.Text="关闭串口"
Button2.Enabled=True
Timer1.Enabled=True
Else
If SerialPort1.IsOpen Then SerialPort1.Close()
Button1.Text="打开串口"
Timer1.Enabled=False
Button2.Enabled=False
End If
End Sub
'待发送数据处理与发送
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim i As Integer
Dim n As Integer
Dim Cmd As String=TextBox1.Text
n=Len(Cmd) \ 2
ReDim fx(n)
For i=1 To n
fx(i)=CByte("&H" & Mid(Cmd, 2 i - 1, 2))
Next
SerialPort1.Write(fx, 1, n) '发送数组fx第1到n数据
End Sub
'数据定时接收与显示
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Dim StrRc As String
Dim i As Integer
Dim n As Integer
n=SerialPort1.BytesToRead '读缓冲区数据量,有数据则接收
If n > 0 Then
ReDim Rc(n)
StrRc=""
For i=1 To n
Rc(i)=SerialPort1.ReadByte
StrRc +=CStr(Hex(Rc(i))) & " " '数据转为16进制显示
Next
TextBox2.Text=StrRc
End If
End Sub
End Class