Raspberry Pi ~ Linux Barcode Scanner HID interfacing

It’s been a bit of a headache finding what I want so I thought I’d leave a trail for the next guy to follow. Here’s how to use a usb hid scanner without tying up the user interface. We are using debian linux and php in this scenario. These are my notes… Your welcome to agree or disagree with the following.

Step 1: Set the scanner to virtual serial port. Yeah I know it’s says HID in the title of this post, but if you want to use the scanner without interrupting the user you’ll want to switch this. The HID keyboard method isn’t really good for linux unless you’re just dedicating the device to the scanner. There are some folks that have done a lot of work with php and scanners that seem to think that the serial port communication method isn’t reliable in php but I’ve not had that experience.

The following commands will help you find out more about your scanner. dmesg | grep usb (right after plug or re-plugin), usb-devices, sudo lsusb -v (more data than you’ll need). Look around your /dev/ folder for devices that show up when you plug & unplug the scanner. You’ll need to properly identify the device to capture data from it.

Step 2: Capture the input device with a script. The script will be running at all times and you’ll need to run it as root. Be sure you got your device file handle right before proceeding. Example script:

<?php
 register_shutdown_function('gnight');
 $handle = fopen( '/dev/ttyACM2', 'r' ); # Open device for Read access
 $inC = 0;
 $buffer = '';
 while (ContinueLoop())    {
     # Read data from device
     $tagid = fgetc($handle);
     if(ord($tagid)>31)  {
         $buffer .= $tagid;
     }
     else    {
         echo "$buffer\n";
         /* 
         * Call other scripts and pass data.
         */
         $buffer = '';
     }      
 }
 function gnight()   {
     global $handle;
     fclose($handle);
 }
 function ContinueLoop() {
     //Check database or file for interupt here. Return false to exit.
     return true;
 }

Hope this helps somebody.

Things to do. Insure a single instance of this script is running per scanner device. Multiples on the same device could really confuse things. Recommend php’s flock.

Author: Joel Caton

Business Consultant and Web Developer from Meridian, MS

Leave a Reply

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