【问题标题】:Missing/lost first character reading serial data from com port to excel从 com 端口读取串行数据到 excel 的第一个字符丢失/丢失
【发布时间】:2020-09-01 13:51:23
【问题描述】:

我有一个连接到 Heidenhain ND221 显示器的测量设备,它可以通过 RS232 串行数据发送它的当前值。我想通过 excel vba 读取该数据以进行一些计算。从数据表中我知道串行设置 (9600,E,7,2) 和 putty 之类的终端正确显示数据:“-___x.xxxx”(+/- 和值之间有 4 个空格)

我使用了我找到的vba代码here

#If VBA7 Then ' Excel 2010 or later
    Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As LongPtr)
#Else ' Excel 2007 or earlier
    Public Declare Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
#End If

Public Sub SerialPort()
    ' open a COM port, transmit a message, gather results, close the port.

    ' open the COM port as file #1
    Debug.Print "Open COM port 3"
    Open "COM3:9600,E,7,2" For Binary Access Read Write As #1

    transmit$ = Chr(2)

    ' transmit a message
    Put #1, , transmit$
    Debug.Print "Message sent."

    ' wait a bit for a response
    Sleep 100

    ' check for received message
    Debug.Print "Look for incoming message."
    On Error Resume Next

    Input #1, receive$
    Debug.Print receive$

    On Error GoTo 0

    ' close the serial port
    Debug.Print "Close COM port."
    Close #1

    Debug.Print "Done."
End Sub

我确实收到了数据,但它在读取前面的 4 个空格时缺少正号或负号。 是串口配置还是输入#语句,我该如何解决? 我还尝试了GetLine Input,结果相同。

谢谢!

【问题讨论】:

  • 显示由 Ctrl+B 或 STX = Chr(2) 触发发送其数据。这完美无瑕。 Debug.Print 不适用于传输$,因为它不是可打印的字符。

标签: excel vba serial-port


【解决方案1】:

好的,我找到了解决方法。我变了

input #1, receive$

Dim receive As String
receive = String(11, " ")
Get #1, , receive

在我添加之前的两行之前,Get # 语句没有显示任何数据。 (我知道数据总是正好有 11 位数字)。

但是,将接收变量初始化为字符串并不能修复 Input # 语句。

现在唯一的问题是,如果您在没有可用数据的情况下尝试接收数据,代码会冻结。见here。 例如,如果显示器关闭,com 端口仍然存在并且可以打开。到目前为止,我发现在这样做之前检查 get 是否会失败。并且一旦尝试它就无法停止或超时。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-22
    • 2018-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多