Archive for the 'Uncategorized' Category

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.