0

我正在通过 COM 端口使用我的条形码扫描仪,使用下面的代码,它模拟 POS 终端并将产品名称及其价格打印到从 MySQL 数据库中提取的屏幕上。问题是,当 com 端口打开并准备读取数据时,例如loop until inkey=chr(13),当我想退出“扫描模式”并获得应付总额时,它将不起作用。

这是用 FreeBasic 编写的,但我对如何解决这个问题的一般概念感兴趣,而不是特定于语言的解决方案。

dim buffer as string*20   'reads a 20 character long string
do
     if open com ("COM6:9600,N,,2" for input as #1) <> 0 then
        print "Unable to open serial port. Press any key to quit application."
        sleep
        end
     end if

    get #1,,buffer
    print buffer 
    close #1
loop
4

1 回答 1

0

我不会一次又一次地循环打开/关闭端口连接。相反,我会在循环之前打开与设备的连接。在循环中,我会检查事件(按键?COM 端口上的新传入数据?)并以某种方式做出反应。最后,如果循环完成,我会关闭连接。

伪代码:

Open Connection
Do This
   PressedKey = CheckForPressedKey()
   If IncomingDataOnComPort? Then
      Load Something From DB ...
   EndIf
Until PressedKey Was ENTER
Close Connection

未经测试的 FreeBASIC 示例:

' Took the COM port parameters from your question. Don't know if correct for the device.
Const ComPortConfig = "COM6:9600,N,,2"

Print "Trying to open COM port using connect string "; Chr(34); ComPortConfig; Chr(34); "..."
If (Open Com ( ComPortConfig For Binary As #1 ) <> 0 ) Then
    Print "Error: Could not open COM port! Press any key to quit."
    GetKey
    End 1
End If

Print "COM port opened! Waiting for incoming data."
Print
Print "Press ENTER to disconnect."
Print

Dim As String ComDataBuffer = "", PressedKey = ""
Do
    ' Key pressed?
    PressedKey = Inkey
    ' Incoming data on COM port ready to be read?
    If Loc(1) > 0 Then
        ComDataBuffer = Space( Loc(1) )
        Get #1, , ComDataBuffer
        Print "Received data on COM port: "; chr(34); ComDataBuffer; chr(34)
    End If
    ' Give back control to OS to avoid high cpu load due to permanent loop:
    Sleep 1
Loop Until PressedKey = Chr(13) 'ENTER

Close #1

Print
Print "Disconnected. Press any key to quit."
GetKey
End 0
于 2017-04-29T17:22:33.187 回答