VisualHMI USB HID scanner: on_key scan code to ASCII

freeFree Technical Resource

This content is free to read, suitable for basic learning and search traffic.

USB Host + customized firmware, directly connected to an HID barcode scanner, with scanned content being passed into Lua via the on_key(key) callback. Applicable to industrial warehousing and production line traceability. HMI&M&DX series + USB interface + customized firmware.

1. API: on_key(key)

where key is a 16-bit unsigned integer: the lower 8 bits represent the USB HID Usage ID (scan code), and the upper 8 bits represent the Shift status (non-zero indicates Shift is pressed, distinguishing between uppercase and lowercase).If the lower 8 bits == 0x28 (Enter), it indicates the end of the barcode, at which point the string is submitted and the buffer is cleared.

2. Lua: Convert HID scan codes to ASCII

by mapping the Usage ID to characters (including uppercase with Shift) using a lookup table. When encountering the 0x28 end character, write to LW2000:

_barCode = ""
usbScanGun = {
  [0x04] = {"a","A"}, [0x05] = {"b","B"}, ... [0x1D] = {"z","Z"},
  [0x1E] = {"1","!"}, [0x1F] = {"2","@"}, ... [0x27] = {"0",")"},
  [0x2C] = {" "," "}, [0x28] = {"n","n"}  -- Enter
}
function on_key(key)
  local usage = key & 0xFF
  local shift = (key >> 8) & 0xFF
  if usage == 0x28 then        -- 结束符
    set_string(VT_LW, 0x2000, _barCode)
    _barCode = ""
    return
  end
  local ch = usbScanGun[usage]
  if ch then
    _barCode = _barCode .. (shift ~= 0 and ch[2] or ch[1])
  end
end

VisualHMI USB HID scanner: on_key scan code to ASCII插图

The essence of the barcode scanner iskeyboard simulation: HID reports scan codes rather than ASCII, which requires manual conversion using a lookup table. The Shift status is stored in the upper 8 bits of key, distinguishing between uppercase and lowercase. 0x28 is the carriage return end character - submit immediately upon receiving, do not wait for timeout. Exclusive to customized firmware.

Compiled from the VisualHMI development documentation of Guangzhou Dacai Technology (hmi-doc.gz-dc.com) and other technical tutorials titled "USB HID Barcode Scanner", copyright reserved by Dacai Technology.

Put this resource to use in a real project?

Go to the Tool Center for message parsing, CRC verification and device debugging, or submit your requirements for selection and integration advice.

Engineer Membership

Turn this article into actionable debugging resources

After activation, you can use advanced message parsing, resource pack downloads, code examples, engineering cases and priority technical support, suitable for real project delivery.

Unlimited Advanced Tools
Resource & Code Packs
Complete Engineering Case Library
Priority Technical Support

Leave a Reply

Your email address will not be published. Required fields are marked *.