关于VB的MSC控件422串口回读数据的问题
用MSCOMM1.OUPUT= " "发指令,MSCOMM1.input读回的数据回显也无误,均为ASCII码。
现在所做的查询指令按照协议规定,发送查询指令 "Q1$ "完毕后,下位机会回答 "Q "。
这时将Q传送回下位机,下位机会将所要查询的坐标值一个字符一个字符的读回,
每读回一个字符需要上位机再将该字符发回下位机,下位机才接着读下一字符。想用
语句MSCOMM1.OUTPUT=MSCOMM1.INPUT 直接读回下位机字符并发送,却无效。单步跟
踪发现input中的值为空。试过将INPUT值放入定义的全局变量中无效,延时无效,由
于input值在text中回显,所以将text值赋给Output仍无效。只有在用
output= "zifu "这种形式发送时,input才会回显正确的字符。请教:如何完成直接取
到下位机传回的数值,并将其送入OUTPUT里再发送回下位机?
代码如下:
Public bb As String
Private Sub Command10_Click()
MSComm1.OutBufferCount = 0 '...清空输出寄存器
If MSComm1.PortOpen = False Then
MSComm1.OutBufferCount = 0
MsgBox "串口关闭,请初始化串口! ", vbExclamation, "警告 "
Else
MSComm1.Output = "Q16$ " '...发送数据(成功传入下位机的回应值)
MSComm1.Output = bb(试验,跟踪显示这里实际并没传入下位机传递的值)
End If
End Sub
Private Sub Mscomm1_Oncomm()
'...通讯事件发生
Select Case MSComm1.CommEvent
Case comEvReceive '...有接受事件发生
Text2.Text = MSComm1.Input '...接受显示数据
bb = MSComm1.Input
MSComm1.InBufferCount = 0 '...清空输入寄存器
End Select
End Sub
[解决办法]
串口是字符设备,其发送与接收都是逐字节进行的,所以你需将接收的数据字符处理后赋值于MSCOMM的属性OUTPUT:
Option Explicit
Private Declare Sub Sleep Lib "kernel32 " (ByVal dwMilliseconds As Long)
Dim strTxt As String
Private Sub cmdSend_Click()
MSComm1.Output = strTxt
End Sub
Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,N,8,1 "
MSComm2.CommPort = 2
MSComm2.Settings = "9600,N,8,1 "
MSComm1.PortOpen = True
MSComm2.PortOpen = True
MSComm2.RThreshold = 1
MSComm1.RThreshold = 1
Text1 = "Q1$ "
'Text1 = "vb编写串口通信程序,可以随便进行汉字、字母、符号的发送和接收. "
'Text1 = "AT+CMGS= " + Chr(13) + Chr(13) + Chr(10) 'rs!tel
'Text1 = "AT+CMGS= " + Chr(13) + Chr(13) + Chr(80) 'rs!tel
'Text1 = "AT+CMGS= " + "vb编写串口通信程序,可以随便进行汉字、字母、符号的发送和接收. " + Chr(10) 'rs!tel
strTxt = Text1
End Sub
Private Sub MSComm1_OnComm()
Dim AscInput As String
Select Case Me.MSComm1.CommEvent
Case comEvReceive
Sleep (50) '延迟
'此处添加处理接收的代码
MSComm1.InputMode = comInputModeText 'Text接收
AscInput = MSComm1.Input
Text3 = AscInput
End Select
End Sub
Private Sub MsComm2_OnComm()
Dim AscInput As String
Select Case Me.MSComm2.CommEvent
Case comEvReceive
Sleep (50) '延迟
'此处添加处理接收的代码
MSComm2.InputMode = comInputModeText 'Text接收
AscInput = MSComm2.Input
MSComm2.Output = Mid(AscInput, 1, 1)
Text2 = AscInput
End Select
End Sub