Berend Vandenbussche
Berend Vandenbussche

Reputation: 106

How to read barcodes in python?

For a school assignment I'm making a "smartfridge", To register the products in the fridge i am using the MCR12-USB barcodescanner: https://www.adafruit.com/product/1203. Connected to a raspberry pi model B3+

I want to get the barcode into a variable to lookup with the UPC api. Any way to get the barcode is good.

I've tried to get the barcode with an input field (barcode setup as keyboard; hidraw0). But the problem with tis approach is that the cursor isn't automatically in the inputfield.

Now I'm trying to get the barcode from the reader via the serial interface (barcode setup as RS232) but i can't get it to work properly, I don't really know which port to open, i've tried serial0, serial1, ttyAMA0 and ttyS0 but on all of them I just get a blank line.

import requests
import serial

def barcode():
    with serial.Serial('/dev/serial0', 9600, timeout=1) as port:
        while True:

            print(port.name)
            line = port.readline()
            print(line)
            url = "https://api.upcdatabase.org/product/%s/%s" % (line, api_key)

            headers = {
                'cache-control': "no-cache",
            }

            response = requests.request("GET", url, headers=headers)

            print("-----" * 5)
            print(line)
            print(json.dumps(response.json(), indent=2))
            print("-----" * 5 + "\n")

I expect the output to be the barcode but I only get a blank line

Upvotes: 3

Views: 3485

Answers (1)

Marcos G.
Marcos G.

Reputation: 3496

Your device is seen by the Rpi as a keyboard by default. If you want to use the USB as a serial port you have to change the configuration.

Follow these steps:

-On a new terminal write: xinput list and find the ID of the barcode reader (a number, id=3 or 10, you should find it by name)

-Then write: xinput test xx where xx is the number you got on the previous step

-Now scan the barcode on top of page 3 of the manual, until you see 02501 coming on the terminal

-Next scan barcode in the middle of page 12, until you see 000603 coming out on the terminal

Now disconnect and reconnect your reader and you should see /dev/ttyUSB0 when you do a ls /dev/tty*. This means your device is ready to be used as a virtual serial port and your code should work now.

Upvotes: 1

Related Questions