C++, C and a Parallel port

About a month ago I went out and purchased a book on C++. I went through it and learned the basics. Yesterday I began work on a program to control inputs and outputs on the LPT port. The interesting part about this is I plan to wire some relays to control back yarded lighting, a few pond pumps and mabey even pool pump and heater.

In this testing stage I just wired some resisters and LED’s onto pins 0 to 7 on the parallel connector. The LED’s I used were 1.5V so I used some resisters to bring down the 5V. If you need any more detail on this feel free to e-mail me.

It’s fairly simple to make the program to run the parallel port. You just have to do some math to figure what values you send out to make certen LED’s light up. The following code is what I used to make sure all 8 outputs are working. It justs randomly flashes the LED’s wired to the parallel plug.

#include <stdio.h>
#include <stdlib.h>
#include <sys/io.h>

#define PORT 0x378 /* use your port address here */

int main(int argc, char *argv[])
{
	int r;
	double l;

	if (iopl(3)) /* you could also use ioperm(PORT, 1, 1) */
	{
		fprintf(stderr, "couldn't get ports,\ntry running as root\n");
		exit(1);
	}

	srand(time(NULL));
	while(1) /*use Ctrl+C to exit */
	{
		l = (double)rand()/(double)RAND_MAX*256;
		r = (int)l;
		outb(r, PORT);
		usleep(500000);
	}

	return 0;
}

I saved the following as test_lpt.c. The compiled the file with the fowloing command.

gcc -O test.c -o test_lpt

Then I executed the new test_lpt that I just compiled and made into a program.

sudo ./test_lpt

Now I had to use sudo because the parallel port only works if your logged in as root in the terminal. The program is a continues loop so to escape out of the loop just press Ctrl + C to shut down the program.

The next program shows how to light up LED’s one and two. We will be sending out a value of 3 to do this.

#define PORT 0x378 /* use your port address here */

int main(int argc, char *argv[])
{
if (iopl(3)) /* you could also use ioperm(PORT, 1, 1) */
{
fprintf(stderr, "couldn't get ports,\ntry running as root\n");
exit(1);
}
outb(3, PORT);
usleep(500000);
return 0;
}

The one peace of code we will be looking at is outb(). The first value, 3, is what value we are sending out to the parallel port. Now this value will tern the LED on Pin 0 and Pin 1. I recommend learning about binary if you plan on building this your self. The second part, PORT, is just specifying what parallel port to use. This was defined at the beginning of the code.

#define PORT 0x378 /* use your port address here */

Once compiled this program should execute then bring you back to the command line. Your LED’s should have changed.

To conclude, I plan on eventually building a board that will hold 8 relay that will let me control multiple devices executed via cronjobs in Ubuntu Linux. I will update this as the project continues.