Linuxで、ppdevを利用して、 パラレルポート(プリンタポート)(/dev/parport0) を読み書きする方法のメモ。
参考ホームページ
/dev/lp0はハンドシェークしながらパラレルポートにデータを出すのに対して、 /dev/parport0を利用するとパラレルポートのピンを直接読み書きすることができる。
通常, /dev/parport0は一般ユーザが読み書きできない設定なので、
su chmod a+rw /dev/parport0
などして読み書き可能にしておく。
以下のプログラムで、 データラインのピンを順番に1にして、 つぎにステータスピン(ackとかbusyなどのピン)の値を読んでいる。 (逆スラッシュが?に文字化けしているので注意)
#include <stdio.h> #include <fcntl.h> #include <sys/ioctl.h> #include <linux/ppdev.h> #include <linux/parport.h> main() { int fd; unsigned char byte; int i, rc, count; //open the printer port fd = open("/dev/parport0", O_RDWR); if(fd==-1) { printf("open error?n"); return 1; } if(ioctl(fd,PPCLAIM)) { printf("PPCLAIM error?n"); close(fd); return 1; } //write a byte to data pins for(i=1;i<256;i=i<<1) { usleep(100000); ioctl(fd, PPWDATA, &i); } //read the status pins ioctl(fd, PPRSTATUS, &byte); printf("status is %2x?n", byte); //close the printer port rc=ioctl(fd, PPRELEASE); close(fd); }
ioctl(fd, XXXXXX);または
ioctl(fd, XXXXXX, &byte);のように操作する。
ioctl(fd, PPDATADIR, &byte);でデータラインの入出力方向を切り替えられるはず(byte=1で出力、byte=0で入力) なのだけど、なぜかこれを行うとデータラインに書きこめなくなった。