[[SiioLaboratory]]

*Linuxでパラレルポート(プリンタポート)を読み書きする [#a49b1131]

Linuxで、ppdevを利用して、
パラレルポート(プリンタポート)(/dev/parport0) を読み書きする方法のメモ。

参考ホームページ
- http://people.redhat.com/twaugh/parport/html/ppdev.html
-- ppdevの使い方に関する資料

** /dev/parport0 [#j8b5bcfa]

/dev/lp0はハンドシェークしながらパラレルポートにデータを出すのに対して、
/dev/parport0を利用するとパラレルポートのピンを直接読み書きすることができる。

通常, /dev/parport0は一般ユーザが読み書きできない設定なので、

 su
 chmod a+rw /dev/parport0

などして読み書き可能にしておく。

** ポートを読み書きするサンプル [#sf2d7d94]

以下のプログラムで、
データラインのピンを順番に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);
 }

** 解説 [#x9c51fbe]

- 使い方は非常に簡単。
他の入出力と同じく、ファイルとしてopenしたあとioctlで、
 ioctl(fd, XXXXXX);
または
 ioctl(fd, XXXXXX, &byte);
のように操作する。

- 簡単だけど罠がひとつ。
 ioctl(fd, PPDATADIR, &byte);
でデータラインの入出力方向を切り替えられるはず(byte=1で出力、byte=0で入力)
なのだけど、なぜかこれを行うとデータラインに書きこめなくなった。

- ioctlの説明は、冒頭のURLの場所の次のページが詳しい。

http://people.redhat.com/twaugh/parport/html/x623.html

トップ   編集 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS