如何通过按回车键退出通过COM端口读取条形码?

How to quit barcode reading thru COM port by hitting an enter?

本文关键字:COM 读取 条形码 何通过 回车 退出      更新时间:2023-10-16

我正在通过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

我不会一次又一次地在循环中打开/关闭端口连接。相反,我会在循环之前打开与设备的连接。在循环中,我会检查事件(按下键?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