0

I'm using my barcode scanner thru a COM port, with the below code, which simulates a POS terminal and prints the product name and its price to the screen pulled from a MySQL database. The problem is that while the com port is open, and ready to read data, the loop until inkey=chr(13) won't work, when I want to quit "scan mode", and get the total amount due, for example.

This is written in FreeBasic, but I'm rather interested in the general concept as to how to solve this problem, not a language specific solution.

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
Rama
  • 3,222
  • 2
  • 11
  • 26
Gabe
  • 11
  • 6
  • The only way I could quit the loop was putting an IF statement in the loop with a specific barcode, by reading which the loop exited, but that's the most awkward solution. – Gabe Apr 07 '17 at 20:58

1 Answers1

0

I would not open/close the port connection in a loop again and again. Instead, I'd open the connection to the device before the loop. In the loop I'd check for events (key pressed? new incoming data on COM port?) and react in some way. Finally, if the loop is finished, I'd close the connection.

Pseudo code:

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

Untested FreeBASIC example:

' 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
MrSnrub
  • 1,123
  • 1
  • 11
  • 19