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