2017-04-07 66 views
0

我使用我的條碼掃描器,通過一個COM端口,下面的代碼模擬POS終端,並將產品名稱和價格打印到從MySQL數據庫中提取的屏幕上。問題是,當com端口打開並準備好讀取數據時,loop until inkey=chr(13)將不起作用,例如,當我想退出「掃描模式」並獲得總金額時。如何通過點擊輸入退出通過COM端口讀取條形碼?

這是用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

我可以退出循環是把IF語句與特定的條形碼循環的唯一方法,通過讀循環退出,但這是最尷尬的解決方案。 – Gabe

回答

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