Search code examples
pythonc++dllbarcode-scannerpyserial

Using C/C++ DLL with Python/Pyserial to communicate with Opticon barcode reader


I have an opticon OPN-2001 barcode scanner that im trying to communicate with. It officially supports C/C++ and .NET but i wanted to use it with python if possible.

I have opened a serial connection to the device (or at least the port(?) but when i use functions from the dll it gives me the communications error (-1) when i am expecting an OK (0). I've never used DLL's or serial communication so bear that in mind.

What im wondering is if i've made some obvious mistakes in calling the DLL-function or using pyserial. Im also very interested in anyone else having a look at their SDK. It seems to be expecting a 4 byte LONG as comPort below. I thought this would work so im a bit stuck. I realize there is only so much you can help without the actual hardware. Thank you for any help however!

Here is the code i have sofar:

from ctypes import *
from serial import *

opticonLib = WinDLL('Csp2.dll')
opticonLib.csp2SetDebugMode(1) #logs to textfile if using debug version of .dll

comPort = 3

opticonSerial = Serial(
port=comPort - 1,
baudrate=9600,
bytesize=EIGHTBITS,
parity=PARITY_ODD,
stopbits=STOPBITS_ONE,
timeout=5
)

if opticonSerial.isOpen():
    print ('Port is open. Using ' + opticonSerial.name + '.')

print (opticonLib.csp2InitEx(comPort)) #Gives -1 instead of 0
opticonSerial.close()

SDK for scanner if you want to dig deeper


Solution

  • Windows keeps a lock on serial ports. Without looking at the SDK, I'm going to guess that csp2InitEx tries to open the serial port itself and when it does so it gets an error from Windows and fails.

    Try not opening the serial port yourself.