7167477af1f743602bfa2a67fc9edb4750001851
[lptgpib.git] / parport.c
1 #include <stdio.h>
2 #include <termios.h>
3 #include <stdint.h>
4 #include <sys/io.h>
5 #include <stdlib.h>
6 #include <assert.h>
7 #include <unistd.h>
8 #include <poll.h>
9
10 static const int port=0x37a;
11
12 #define LENGTH(x) (sizeof(x)/sizeof(*(x)))
13
14 static volatile struct termios tios;
15
16 static void cleanup(void) {
17   tcsetattr(0,TCSANOW,(struct termios *)&tios);
18 }
19
20 int main(void) {
21   uint8_t out=0x24;
22   if (ioperm(port,1,1)!=0) {
23     fprintf(stderr,"ioperm 0x%x: %m\n",port);
24     exit(EXIT_FAILURE);
25   }
26   int i=tcgetattr(0,(struct termios *)&tios);
27   assert(i==0);
28   atexit(cleanup);
29   struct termios tios_raw=tios;
30   cfmakeraw(&tios_raw);
31   i=tcsetattr(0,TCSANOW,&tios_raw);
32   assert(i==0);
33   for (;;) {
34     static const struct item {
35       const char *name;
36       uint8_t mask;
37       char key;
38     } items[]={
39       {"DAV=pin1"  ,0x01,'1'},
40       {"NRFD=pin14",0x02,'2'},
41       {"NDAC=pin16",0x04,'4'},
42       {"ATN=pin17" ,0x08,'8'},
43       {"bidir"     ,0x20,'b'},
44     };
45     outb(out,port);
46     usleep(1000000/10);
47     uint8_t in=inb(port);
48     printf("out=0x%02x in=0x%02x",out,in);
49     for (const struct item *item=items;item<items+LENGTH(items);item++)
50       printf(" %s:out=%d,in=%d;'%c'",item->name,!!(out&item->mask),!!(in&item->mask),item->key);
51     putchar('\r');
52     fflush(stdout);
53     struct pollfd pollfd;
54     pollfd.fd=STDIN_FILENO;
55     pollfd.events=POLLIN;
56     switch (poll(&pollfd,1,0)) {
57       case 1: {
58         char c;
59         ssize_t got=read(STDIN_FILENO,&c,1);
60         assert(got==1);
61         if (c==27||c==3||c=='\r') {
62           putchar('\n');
63           exit(EXIT_FAILURE);
64         }
65         for (const struct item *item=items;item<items+LENGTH(items);item++)
66           if (c==item->key)
67             out^=item->mask;
68         } break;
69       case 0:
70         break;
71       case -1:
72         abort();
73     }
74   }
75 }