如何通过按回车键退出通过COM端口读取条形码?
How to quit barcode reading thru COM port by hitting an enter?
我正在通过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
相关文章:
- 理解boost::asio-async_read在无需读取内容时的行为
- 使用新行和不使用新行读取文件
- 读取文件并输入到矢量中
- 如何读取 C++ SAFEARRAY**,该 SAFEARRAY** 是 COM 互操作的结果,其中 C# 返回值为
- 从 COM 对象快速读取西里尔字母
- 如何通过按回车键退出通过COM端口读取条形码?
- COM 端口C++读取0xFF
- IStream COM 读取到缓冲区,然后通过 winsock 发送
- 带虚拟COM端口的USB串行设备-如果使用带USB路径的CreateFile(),则ReadFile()读取零字节
- 设置com类的数组会触发读取访问
- USB串行虚拟COM端口:读取不工作,但写入工作
- 使用tserial.cpp驱动程序读取COM端口时的延迟
- 读取 COM 端口数据C++
- 读取后 COM 端口无法写入
- 如何使用 boost 从 com 端口读取未定义的字节数
- 尝试使用 c++ 从 com 端口读取写入数据
- 使用 C++ 从 COM 端口读取文件时出错
- 读取阻塞模式从com端口rs232
- c++程序在读取COM端口时冻结
- 使用 C++ 从 COM 端口读取输出数据