LPT programming example in C for ubuntu linux

I wanted to try out LPT printer port programming for upcoming other project. After hours of learning and searching, I came up with this piece of code.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/io.h>
#include <sys/types.h>
#include <fcntl.h>

#define BASEPORT 0x378 /* lp1 */

int main()
{
  char c;
  int n, tem;

   printf("Hit enter to stop\n");

  if (ioperm(BASEPORT, 3, 1)) {perror("ioperm"); exit(1);}

  tem = fcntl(0, F_GETFL, 0);
  fcntl (0, F_SETFL, (tem | O_NDELAY));

  while (1) {
    n = read(0, &c, 1);
    if (n > 0) break;

     outb(255, BASEPORT);
     usleep(250000);
     outb(0, BASEPORT);
     usleep(250000);
  }

  fcntl(0, F_SETFL, tem);
  outb(0, BASEPORT);

  if (ioperm(BASEPORT, 3, 0)) {perror("ioperm"); exit(1);}

  exit(0);

}

I compiled it with command where lpt.c is source code and lpt is program name compiled.

gcc lpt.c -O2 -o lpt

I used LED with 550 ohms resistor in series and soldered it between pin 2 and 20 to test out this program.

5 Responses to “LPT programming example in C for ubuntu linux”


  1. 1Magnus

    Thanks a lot man! I was looking for this but everything seemed to be wrong for some reason until I found this. This worked for me. Thanks.

  2. 2Riccardo

    Hello,
    could you add some comments to you code so that we can understand it?
    I’d like to learn to open it and read data…what documentation do i need?

  3. 3david

    Could I use your code to writing my bachelor of science dissertation? I’m looking forward your respond.

  4. 4pk

    Work well under ubuntu 9.10 thanks

  5. 5Omar Ramirez

    Hello i am from Peru.
    I am a proggramer of softwers in Java.
    I works in Roche Diagnostics in Lima, we have a analyzer, that are usefull in laboratories, they can make test on samples of blood. You can see one of them here http://images.google.com.pe/images?hl=es&source=hp&q=hitachi 917&um=1&ie=UTF-8&sa=N&tab=wi
    I made a software that use a information from the analyzer, normaly we can save this information in a diskette or a usb driver, but the problem is that this analyzer Hitachi 917 not export this information to a floopy or a usb port, it prints this information in a printer (this printer uses lpt1 port). I would like to make some device that takes this information from the cable and save this to a floopy or a usbdriver. There is something that can do that?. Thanks for aswers. Omar

Leave a Reply