我正在使用我的条形码扫描仪通过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
答案 0 :(得分: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