这几天正在使用VB写一个通过串口的方式实现ModBus协议通讯的小程序,结果发现在接收数据时总是出现问题,感觉很怪异,关键代码如下:打开串口前的初始化设置
MSComm1.CommPort = 3
MSComm1.Settings = "19200,e,8,1"
MSComm1.InputMode = 0
发送前做的设置
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.Output = hexchrgroup此处我使用一个定时器延时的方法来触发下面的接收程序
接收程序代码
Dim Hexchr As String, hexstring As String, i As Integer, j As Integer, hexdisp As String
Dim aa() As Byte
Dim tempstr As String Label24.Caption = Str(MSComm1.InBufferCount) hexstring = MSComm1.Input If Err Then '显示出错信息
MsgBox Error$, 48, "错误信息"
Exit Sub '十六进制显示
End If i = Len(hexstring)
tempstr = ""
For j = 1 To i
Hexchr = Mid(hexstring, j, 1)
If Asc(Hexchr) < 16 Then
tempstr = tempstr & "0" & Hex(Asc(Hexchr)) & " "
Else
tempstr = tempstr & Hex(Asc(Hexchr)) & " "
End If
Next j
text1.text = tempstr另外接收到的数据也有问题
发送的数据:01 06 0001 0002 59 CB
接收的数据:01 06 00 01 00 02 59 00
MSComm1.CommPort = 3
MSComm1.Settings = "19200,e,8,1"
MSComm1.InputMode = 0
发送前做的设置
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.Output = hexchrgroup此处我使用一个定时器延时的方法来触发下面的接收程序
接收程序代码
Dim Hexchr As String, hexstring As String, i As Integer, j As Integer, hexdisp As String
Dim aa() As Byte
Dim tempstr As String Label24.Caption = Str(MSComm1.InBufferCount) hexstring = MSComm1.Input If Err Then '显示出错信息
MsgBox Error$, 48, "错误信息"
Exit Sub '十六进制显示
End If i = Len(hexstring)
tempstr = ""
For j = 1 To i
Hexchr = Mid(hexstring, j, 1)
If Asc(Hexchr) < 16 Then
tempstr = tempstr & "0" & Hex(Asc(Hexchr)) & " "
Else
tempstr = tempstr & Hex(Asc(Hexchr)) & " "
End If
Next j
text1.text = tempstr另外接收到的数据也有问题
发送的数据:01 06 0001 0002 59 CB
接收的数据:01 06 00 01 00 02 59 00
解决方案 »
- 如何用函数动态生成新的控件
- 请教一个ESC/POS命令控制票据打印机的问题
- 水晶报表不支持模糊查询?
- 问个报表问题,望各位大哥指点,见者有分哦
- 从这数据库服务器导入到那数据库服务器的问题
- vb打包
- 怎样实现可更改密码的加密登录?
- VB中有没有像HASHTABLE一样的东西呢?
- 请教一下如何在程序中调用别的应用程序?
- 我开发的VB程序,在台式机上的CRT显示器800×600下显示很好,但到了笔记本电脑的液晶显示器上的800×600时字体显示非常粗糙难以入目。若在液晶显示器的1024×768下显示,字体虽然好看,但程序运行后的窗口只占液晶显示器的一部分,相当一部分屏幕没有
- adodc的记录指针移动
- formatnumber问题目
Option Explicit
Dim tempstr As String
Private Sub Form_Load()
MSComm1.CommPort = 3
MSComm1.Settings = "19200,e,8,1"
MSComm1.InputMode = comInputModeBinary
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.RThreshold = 1
MSComm1.PortOpen = True
End SubPrivate Sub MSComm1_OnComm()
Dim aa() As Byte
Dim j As Integer
Select Case MSComm1.CommEvent
Case 2
Label1.Caption = Str(MSComm1.InBufferCount)
aa = MSComm1.Input
For j = 0 To UBound(aa)
tempstr = tempstr & Right("0" & Hex(aa(j)), 2) & " "
Next j
Text1.Text = tempstr
End Select
End Sub