LPT programming example in C for ubuntu linux

A while back I wanted to try out LPT printer port programming for upcoming project. After hours of learning, testing and searching, I came up with fallowing piece of code what finally worked for me. This example code makes LED blink in rate of 2 blinks per second wich is soldered between ground and any of the data pins.

#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 any key to stop\n");
	
	//set permissions to access port
	if (ioperm(BASEPORT, 3, 1)) {perror("ioperm"); exit(1);}
	
	tem = fcntl(0, F_GETFL, 0);
	fcntl (0, F_SETFL, (tem | O_NDELAY));
	
	//main loop where actual blinking is done
	while (1) {
		//if some key is pressed, break out from loop
		n = read(0, &c, 1);
		if (n > 0) break;
		
		//write 'on' bit on all data pins and wait 1/4 second
		outb(255, BASEPORT);
		usleep(250000);
		
		//write 'off' bit on all data pins and wait 1/4 second
		outb(0, BASEPORT);
		usleep(250000);
	}
	
	fcntl(0, F_SETFL, tem);
	outb(0, BASEPORT);
	
	//take away permissions to access port
	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

After that check that program has excecute permissions and run it with command.

./lpt

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

You may also like to check out these links

Magnus #
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.
No gravatar aivable
Riccardo #
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?
No gravatar aivable
david #
Could I use your code to writing my bachelor of science dissertation? I'm looking forward your respond.
No gravatar aivable
pk #
Work well under ubuntu 9.10 thanks
No gravatar aivable
Joe L #
This looks like just what I need!

I've noticed that my lpt port seems to be /dev/lpt0 though. Do you know the BASEPORT value that should be used for this (how do you find out?)... or is this still the same value?
janar jürisson profile I am web developer who is interested in creating clean, fast and clutter free pages. Trying to think more "User-centered" because after all they will be using apps that I create. Also fan of shared information, inspiration and alternative thinking because information gives you freedom.