vb.net串口使用方法的简单介绍
vb.net程序如何实现向电脑的Com口发送一段字符串信息,之后再接收显示发送的字符串信息?
'vb.net的串口接收数据要用到委托
创新互联-专业网站定制、快速模板网站建设、高性价比西乌珠穆沁网站开发、企业建站全套包干低至880元,成熟完善的模板库,直接使用。一站式西乌珠穆沁网站制作公司更省心,省钱,快速模板网站建设找我们,业务覆盖西乌珠穆沁地区。费用合理售后完善,十年实体公司更值得信赖。
Delegate Sub SetTextCallback(ByVal InputString As String) '声明一个委派类,并声明符合函数参数有一个,而其型态是字符串
Private Sub ShowString(ByVal comData As String)
txt_Re.Text = comData '将收到的数据入接收文字框中--- txt_Re.Text 是接收用的文本框
txt_Re.SelectionStart = txt_Re.Text.Length
txt_Re.ScrollToCaret()
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived‘自动接收事件
Dim inData As String = SerialPort1.ReadExisting
Dim d As New SetTextCallback(AddressOf ShowString)
Invoke(d, inData)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click '发送指令
SerialPort1.Write("123")
End Sub
vb.net中串口发送数据问题
串口通讯本来就是传送的字符的Ascll码。如果你传送的是二进制数据,可以把二进制的数据每8bit换算成一个对应的字符传过去,接收端逆向转换过来即可。
VB.net 串口传送回数据处理的问题
使用委托方式处理:
Public Class Form1
Dim mSTR As String
Dim strData As String
Dim strDat As String
Dim mRecvByte() As Byte
Dim Hexsj As String
Dim form2 As Form
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim mSize As Integer = Me.SerialPort1.BytesToRead
ReDim mRecvByte(mSize - 1)
SerialPort1.Read(mRecvByte, 0, mSize)
BeginInvoke(New EventHandler(AddressOf ONMLoadA), SerialPort1.BytesToRead()) '使用委托方式显示接收到的字符串
End Sub
Sub ONMLoadA(ByVal sender As System.Object, ByVal e As System.EventArgs) '委托
strDat = ""
TextBox1.Text = ""
Dim i As Integer
For i = 0 To UBound(mRecvByte) 'mSize - 1
strData = strData IIf(mRecvByte(i) 15, Hex(mRecvByte(i)), "0" Hex(mRecvByte(i))) " "
Next
Dim sj As Byte
For i = 1 To Len(strData) Step 3 '处理为ASCII字符
sj = Val("H" Mid(strData, i, 2))
If sj 32 Or sj 128 Then '当接收字节中有Chr(0)时,其后字符被切割
strDat = strDat "."
Else
strDat = strDat Chr(sj)
End If
Next
TextBox1.Text = strDat '显示字符
TextBox2.Text = strData '显示为16进制
TextBox3.Text = Len(strData) / 3
End Sub
VB.net 串口发送数据
你可以这样操作:
Form1.BeginInvoke(Sub()
'一些操作
End Sub)
这样主线程就会放下手里的事情并执行Sub里的操作了
当前名称:vb.net串口使用方法的简单介绍
网页URL:http://scyanting.com/article/dodcppd.html