Saturday, April 2, 2011

Interfacing Parallel Port using Qt

I've been in a situation today where I wanted a quick app to interact with the parallel port. Although it is no big deal, it was my first time. So I wanted to document it and make a simple application.

There is no Qt API to access the parallel port, so there was no other way but using an extra DLL: inpout32.dll. The core of code in brief is like that:

Note: the DLL was not available by default. So I downloaded it and Had the choice to put it in C:\Windows\System32 or just point to it in the application's folder.

*.h
#include <windows.h>

/* prototype (function typedef) for DLL function Inp32: */
typedef short _stdcall (*inpfuncPtr)(short portaddr);
typedef void _stdcall (*oupfuncPtr)(short portaddr, short datum);

private:
    HINSTANCE hLib;
    inpfuncPtr inp32;
    oupfuncPtr oup32;
    short portData; //must be in hex
    int portNumber; //must be in hex

*.cpp
/* Load the library */
hLib = LoadLibraryA("inpout32.dll");

/* get the address of the function */
inp32 = (inpfuncPtr) GetProcAddress(hLib, "Inp32");
oup32 = (oupfuncPtr) GetProcAddress(hLib, "Out32");
Note: I faced an encoding error with LoadLibrary(). so I used LoadLibraryA() instead.

Reading
portData = (inp32)(portNumber);

Writing
(oup32)(portNumber, portData);

A useful hint for converting from QString to Hex/Binary, and vise versa
//QString to Hex
portNumber = myString.toInt(&ok, 16);

//Hex to QString
myString = QString::number(portData, 16);

Note: Icons in this application are free! http://www.freedesktop.org/


Download source code
Download executable

Resources:
Parallel Port Output On Windows XP using Qt4 and C++
MinGW: char to WCHAR

3 comments:

  1. Really helpful, thanks a million.

    ReplyDelete
  2. I modified your code a little because I have Windows 7 64bit, Qt 5.3.0 and MinGW.
    Here are my modifications for mainwindow.cpp:
    //==========================================================
    QLibrary m_parallelPortDll;
    m_parallelPortDll.setFileName("C:\\Temp\\inpout32.dll");

    /* Load the library */
    if(m_parallelPortDll.load()==false)
    {
    errorFlag = true;
    QMessageBox::warning(this, "Error", "LoadLibrary Failed: inpout32.dll");
    return;
    }

    /* get the address of the function */
    inp32 = (inpfuncPtr) m_parallelPortDll.resolve("Inp32");
    if (inp32 == NULL)
    {
    QMessageBox::warning(this, "Error", "GetProcAddress for Inp32 Failed");
    return;
    }
    oup32 = (oupfuncPtr) m_parallelPortDll.resolve("Out32");
    if (oup32 == NULL)
    {
    errorFlag = true;
    QMessageBox::warning(this, "Error", "GetProcAddress for Oup32 Failed");
    return;
    }
    //=============================================
    And this little thing for pro file:
    QT += core gui
    greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

    ReplyDelete