brechmos
Posts: 4
Joined: Sun Sep 08, 2013 7:45 pm

USB bar code scanner

Sun Sep 08, 2013 7:53 pm

Hi All,

I am completely stuck. I have a reasonably standard USB bar code scanner that I have plugged into my Pi. It creates a /dev/hidraw0. The bar code scanner comes up as a "keyboard" on a computer (tried on several). What I want to do is have a program running in the background that reads the bar code scanner as a "keyboard" without having a terminal open.

The code that I am using is below. I found this type of thing on another board.

Code: Select all

import sys

fp = open('/dev/hidraw0', 'rb')

while True:
	buffer = fp.read(8)
	for c in buffer:
		if ord(c) > 0:
			print ord(c)
	print "\n"
I have a book I am using as a test case and the ISBN is 9780310721567.

When I run the code and scan the book I get:

38
36
37
39
32
30
39
36
31
30
34
35
36
40

I am really confused. I was hoping that somehow I could get a string, or the ASCII code of the ISBN. I am honestly not sure what the codes above are as they don't appear to coincide with the ISBN number.

Any help or thoughts would be greatly appreciated.

User avatar
rurwin
Forum Moderator
Forum Moderator
Posts: 4258
Joined: Mon Jan 09, 2012 3:16 pm
Contact: Website

Re: USB bar code scanner

Sun Sep 08, 2013 8:18 pm

I've had a look, and I can't explain it. Are you sure you have the scanner configured to read EAN-13 barcode?

User avatar
joan
Posts: 14004
Joined: Thu Jul 05, 2012 5:09 pm
Location: UK

Re: USB bar code scanner

Sun Sep 08, 2013 8:41 pm

You could try

od -x </dev/hidraw0

from the command line.

kwilkyn
Posts: 6
Joined: Thu Aug 29, 2013 12:20 am

Re: USB bar code scanner

Sun Sep 08, 2013 9:48 pm

It may not be that bad.
If you look at the codes you're getting back they are consistent: 1 on the barcode gives 30, 2 gives 31, and so on.
This could be (digit value)+29, (ASCII of digit) -19 or even (hexadecimal ASCII of digit ) -1.
Then the code wraps round, using 39 (which should be 10) to indicate zero, like an old-fashioned telephone dial.
Lastly there's an extra code on the end (40), which could be an 'that's all, folks' marker or some sort of checksum on the data. (The last 7 is the ISBN checksum digit). It would interesting to see if this is 40 on other books.
It's possible that your reader thinks it's reading a different breed of barcode, but it should be fairly simple to translate into decimal with a bit of maths.
Hope that helps.

User avatar
redhawk
Posts: 3465
Joined: Sun Mar 04, 2012 2:13 pm
Location: ::1

Re: USB bar code scanner

Sun Sep 08, 2013 9:50 pm

There are several web sites with bar code pattern generators, I'm sure with a bit a trial an error it should be possible to decipher the results from your bar code.

Richard S.

User avatar
rpdom
Posts: 14416
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: USB bar code scanner

Sun Sep 08, 2013 10:30 pm

kwilkyn wrote:It may not be that bad.
If you look at the codes you're getting back they are consistent: 1 on the barcode gives 30, 2 gives 31, and so on.
This could be (digit value)+29, (ASCII of digit) -19 or even (hexadecimal ASCII of digit ) -1.
Then the code wraps round, using 39 (which should be 10) to indicate zero, like an old-fashioned telephone dial.
Lastly there's an extra code on the end (40), which could be an 'that's all, folks' marker or some sort of checksum on the data. (The last 7 is the ISBN checksum digit). It would interesting to see if this is 40 on other books.
It's possible that your reader thinks it's reading a different breed of barcode, but it should be fairly simple to translate into decimal with a bit of maths.
Hope that helps.
This sounds quite likely. I believe some barcodes use 10 instead of 0 in some cases, which might be printed as an "X". I feel I ought to look a bit closer at the binary values to try and make more sense of them.

brechmos
Posts: 4
Joined: Sun Sep 08, 2013 7:45 pm

Re: USB bar code scanner

Sun Sep 08, 2013 11:26 pm

That is a great idea to use od. I had not thought of that. [minutes later...] Unfortunately, it wasn't more help to me.

rurwin: The scanner is setup to read a whole bunch of different code types. The one I actually want is code128 which is what I will further test below.

kwilkyn: I noticed the pattern too but was a little confused why the 0 was greater than 9.

I created two bar codes (code128 which is actually what i want) with some reasonably standard text. I plugged the bar code scanner into my MAC laptop and did cat /dev/ttys001. It printed out the codes perfectly.

Maybe more to the problem: The other thing I don't understand is why there is no /dev/ttySxxx created when I plug the scanner into the raspberry pi. The only thing I see created is the /dev/hidraw0. It is almost like the raspberry pi is not creating the /dev/ttySxxx devices automatically. It did create a /dev/ttys001 on my mac laptop.

I tried it now on another linux box and it appeared to come out the same as on the Raspberry pi.

I will look at the coding some more but if anyone has an idea why the /dev/ttySxxx is not created, I would be greatful for any ideas.

User avatar
redhawk
Posts: 3465
Joined: Sun Mar 04, 2012 2:13 pm
Location: ::1

Re: USB bar code scanner

Sun Sep 08, 2013 11:35 pm

Perhaps http://en.wikipedia.org/wiki/Code_128 maybe of some use??

Richard S.

brechmos
Posts: 4
Joined: Sun Sep 08, 2013 7:45 pm

Re: USB bar code scanner

Mon Sep 09, 2013 12:42 am

Ah hah. Thank you all.

So, it is returning to me the HID (human interface device) keyboard mapping. Briefly, the value is in the left column and the mapped keyboard character is in the right. If it is preceded by a "2" then this means shift key and you get the other character (e.g., upper case)

Code: Select all

4	a
5	b
6	c
7	d
8	e
9	f
10	g
11	h
12	i
13	j
14	k
15	l
16	m
17	n
18	o
19	p
20	q
21	r
22	s
23	t
24	u
25	v
26	w
27	x
28	y
29	z
30	1
31	2
32	3
33	4
34	5
35	6
36	7
37	8
38	9
39	0
40	
41	
42	
43	:
44	
45	-
46	=
47	[
48	]
49	\
50	
51	;
52	'
53	
54	,
55	.
56	/
For reference, http://source.android.com/devices/tech/ ... vices.html (on that page under "HID Keyboard and Keypad Page (0x07)"

If I find or create some python code I'll post here.

Again, thanks for all the ideas.

brechmos
Posts: 4
Joined: Sun Sep 08, 2013 7:45 pm

Re: USB bar code scanner

Mon Sep 09, 2013 1:33 am

And as a final note. Here is the code I created and which appears to work (but check for yourselves). It is not pretty code. This is my quick attempt to get things working.

Thanks again for all the pointers.

Code: Select all

import sys

hid = { 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm', 17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y', 29: 'z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ', 45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';' , 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'  }

hid2 = { 4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M', 17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y', 29: 'Z', 30: '!', 31: '@', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ', 45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':' , 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'  }

fp = open('/dev/hidraw0', 'rb')


ss = ""
shift = False

done = False

while not done:

	## Get the character from the HID
	buffer = fp.read(8)
	for c in buffer:
		if ord(c) > 0:

			##  40 is carriage return which signifies
			##  we are done looking for characters
			if int(ord(c)) == 40:
				done = True
				break;

			##  If we are shifted then we have to 
			##  use the hid2 characters.
			if shift: 

				## If it is a '2' then it is the shift key
				if int(ord(c)) == 2 :
					shift = True

				## if not a 2 then lookup the mapping
				else:
					ss += hid2[ int(ord(c)) ]
					shift = False

			##  If we are not shifted then use
			##  the hid characters

			else:

				## If it is a '2' then it is the shift key
				if int(ord(c)) == 2 :
					shift = True

				## if not a 2 then lookup the mapping
				else:
					ss += hid[ int(ord(c)) ]
			
print ss

dmb
Posts: 38
Joined: Wed May 30, 2012 9:33 am

Re: USB bar code scanner

Thu Sep 12, 2013 10:20 pm

Sorry to jump on this thread but it's the closest I can find to my barcode scanning problem. I have a wireless scanner - usb dongle - that creates /dev/hidraw0 when plugged in. This disappears when the dongle is unplugged. There's also a /dev/hidraw1 that exists permanently. However when I run the code at the top it just waits forever. Scanning a barcode makes no difference - scanner beeps to indicate a good scan, nothing echoed. Same if I run the C code available around the web (in blocking mode).

All the instructions I have are in Chinese, other than a page of barcodes for setting the scanner. So I'm not really sure what I need to set up, e.g. "serial" or "keyboard wedge" etc.! If I plug the dongle into a Windows it shows up in the device manager. Scanning a barcode in a command window gives nothing - I thought I'd see the barcode numbers echoed at the command prompt ?

Any tips welcome, you can tell I'm at the extreme newbie end of the barcode-scanning scale !

David

dmb
Posts: 38
Joined: Wed May 30, 2012 9:33 am

Re: USB bar code scanner

Sat Oct 05, 2013 3:55 pm

Right, apologies for a reply to my own post, but I've got a little further before hitting a block.

It seems the scanner was not working ! I returned it and got a replacement, which is much more responsive. For example, I can plug the dongle into a PC running a browser with the cursor in the address bar, and on scanning an EAN code, the appropriate numbers pop into the textbox as if I'd entered them on the keyboard. So, expected behaviour at least !

However when I plug the dongle into my Pi, I get no response. /dev/hidraw1 is created, but nothing reads from it, not python, C or even "od -x < /dev/hidraw1". It just sits in a read state, never reading anything. FWIW, it's device 5 in the list below.

Code: Select all

# lsusb
Bus 001 Device 002: ID 0424:9512 Standard Microsystems Corp.
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub
Bus 001 Device 003: ID 0424:ec00 Standard Microsystems Corp.
Bus 001 Device 004: ID 1941:8021 Dream Link WH1080 Weather Station / USB Missile Launcher
Bus 001 Device 005: ID 04d8:0055 Microchip Technology, Inc.
# ls -l /dev/hidraw1
crw------- 1 root root 249, 1 Jan  1  1970 /dev/hidraw1
# lsusb -v
[snip]
Bus 001 Device 005: ID 04d8:0055 Microchip Technology, Inc.
Device Descriptor:
  bLength                18
  bDescriptorType         1
  bcdUSB               2.00
  bDeviceClass            0 (Defined at Interface level)
  bDeviceSubClass         0
  bDeviceProtocol         0
  bMaxPacketSize0         8
  idVendor           0x04d8 Microchip Technology, Inc.
  idProduct          0x0055
  bcdDevice            0.01
  iManufacturer           1
  iProduct                2
  iSerial                 0
  bNumConfigurations      1
  Configuration Descriptor:
    bLength                 9
    bDescriptorType         2
    wTotalLength           41
    bNumInterfaces          1
    bConfigurationValue     1
    iConfiguration          0
    bmAttributes         0xc0
      Self Powered
    MaxPower              100mA
    Interface Descriptor:
      bLength                 9
      bDescriptorType         4
      bInterfaceNumber        0
      bAlternateSetting       0
      bNumEndpoints           2
      bInterfaceClass         3 Human Interface Device
      bInterfaceSubClass      1 Boot Interface Subclass
      bInterfaceProtocol      1 Keyboard
      iInterface              0
        HID Device Descriptor:
          bLength                 9
          bDescriptorType        33
          bcdHID               1.11
          bCountryCode            0 Not supported
          bNumDescriptors         1
          bDescriptorType        34 Report
          wDescriptorLength      63
         Report Descriptors:
           ** UNAVAILABLE **
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x81  EP 1 IN
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval               1
      Endpoint Descriptor:
        bLength                 7
        bDescriptorType         5
        bEndpointAddress     0x01  EP 1 OUT
        bmAttributes            3
          Transfer Type            Interrupt
          Synch Type               None
          Usage Type               Data
        wMaxPacketSize     0x0008  1x 8 bytes
        bInterval               1
Device Status:     0x0a08
  (Bus Powered)
I'll keep plugging away, any hints in the meantime would be very useful.

Thanks,

David

EDIT: got it working, something in the C code that had failed also made the dongle need to be unplugged and re-plugged. It's odd, if I bomb out of a programme on an exception it seems to need the unplug/replug to make it work again, not sure why.
All working great now under normal circumstances - my pi now reads barcodes, looks them up against an online service and says what the thing scanned is using the Festival voice synth package !

SpiritualMadMan
Posts: 2
Joined: Tue Sep 24, 2013 6:20 pm

Re: USB bar code scanner

Tue Jun 17, 2014 4:01 pm

import sys

fp = open('/dev/hidraw0', 'rb')

while True:
buffer = fp.read(8)
for c in buffer:
if ord(c) > 0:
print ord(c)
print "\n"


Instead of print ord(c)

try print c or print str(c) That should give you plain text of what you are scanning...

you can also add tStr = ' ' before the while loop and then replace or add the print statement with tStr = tStr + c

When you exit tStr should contain the scanned data.

Hope this helps...

Example:

import sys

fp = open('/dev/hidraw0', 'rb')
tStr = ''
while True:
buffer = fp.read(8)
for c in buffer:
if ord(c) > 0:
#print ord(c)
tStr = tStr + c

print tStr + "\n"

riklaunim
Posts: 265
Joined: Tue Apr 22, 2014 7:34 pm

Re: USB bar code scanner

Tue Jun 17, 2014 4:12 pm

You could try using some pyusb code to catch data from that scanner. You can get my code from that link. It converts those numbers to actual letters and digits from the bar code.

chichara
Posts: 2
Joined: Wed Sep 17, 2014 2:04 am

Re: USB bar code scanner

Mon Nov 24, 2014 9:53 am

hi brechmos, thanks for your code.
I've tried it and success to read the barcode.
But, what if i used to read some barcode without execute the program every time i scan the barcode?
I mean how to make the program looping?
I try using while true, but it said syntax error.
Could u please help me?
Im really new with raspberry, also python. =D

jos0405
Posts: 1
Joined: Tue Sep 10, 2013 9:15 am

Re: USB bar code scanner

Tue Jun 30, 2015 6:25 am

I had similar issues with barcode scanning on the Raspberry Pi.
When tried to scan barcodes into a text editor, only skipped a line for me.
In terminal a long character string came up starting with 3A- ... etc.

It took me some time to figure out

The scanner was set in ALT mode. This is normal when you use it for a Windows mashine, but not on Linux. ALT mode adds ALT+NUMBER combination to the scanned values and this is why its not visible in a text editor, but visible in terminal.

I started to experiment around with other modes available for my very generic barcode scanner, and found, that LOWERCASE mode will do the trick. Now the barcode reading works like a charm, without any python script.

Check your programming guide of your scanner, and try to switch the scanning mode. It usually goes by scanning a PROGRAM START barcode from the booklet, than LOWERCASE barcode and PROGRAMMING END barcode.

Good luck :)

rajatkusumwal
Posts: 1
Joined: Thu Sep 17, 2015 10:12 am

Re: USB bar code scanner

Thu Sep 17, 2015 10:18 am

@brenchmos: Can you please tell me which bar-code reader are you in particularly using?

pkumar290
Posts: 1
Joined: Fri Dec 04, 2015 5:23 am

Re: USB bar code scanner

Fri Dec 04, 2015 12:40 pm

hi, i try this code but it wait for untill scan barcode and not allow to complete execution of program.
anybody can tell me how to write code which run one time and give result only when barcode is scanned.

Return to “HATs and other add-ons”