Tuesday, March 14, 2006

LPT1 stepper motor control

Last Sunday, I was coding some modules for our RDBMS project and playing Dungeon Siege: Legend of Aranna (quite old but it would be a waste of time if I did not) in parallel. I received a phone call asking a favor to write a program for sending signals through the parallel port. It sounds a little scary at first because I did not have any idea on parallel port interfacing.


Let me explain the project.


The project is a Car Control System. They have 2 bipolar stepper motors. One is responsible for the forward-reverse function and the other one is for the left-right function.


Signals recognized by the floppy drive stepper motor:


Clockwise 18-degree turn


1001      or      0x9
0110 or 0x6

Counterclockwise 18-degree turn


0110      or      0x6
1001 or 0x9

Now, how is it possible to send these signals using the parallel port? Not all 25 pins are needed. For this project, only the data pins are needed.


Pin         Function
2 D0
3 D1
4 D2
5 D3
6 D4
7 D5
8 D6

LPT1 is usually 0x378; having this knowledge, everything comes in trivial.


In file lptcontrol.c


#include <conio.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
short data;

if(argc<2) {
printf("Usage\n\n");
printf("lptcontrol.exe [option] [data]\n\n");
return 0;
}

/* a read function is not necessary for this project
included for additional info */

if(!strcmp(argv[1],"read")) {
data = _inp(0x378);
printf("Data from parallel port: ");
printf("%d",data);
}

if(!strcmp(argv[1],"write")) {
_outp(0x378,atoi(argv[2]));
printf("Data written to parallel port: ");
printf("%s",argv[2]);
}
return 0;
}

If you want a constant turn you can achieve it through a loop.



while(1) {
_outp(0x378, 0x9);
_outp(0x378, 0x6);
}

This will result to a motor spinning clockwise. C program above is written for Windows OS.

No comments: