start with clock
[des2015.git] / mart / ex11 / ex11.c
1 #include <stdio.h>
2 #include <signal.h>
3 #include <unistd.h>
4 #include <sys/mman.h>
5 #include <sys/io.h>
6
7 #include <native/task.h>
8 #include <native/timer.h>
9 #include <native/intr.h>
10
11 #include <rtdk.h>
12
13 #define LPT1IRQ 7
14 #define TICKS 5
15 #define MAXX 10
16 #define MAXY 7
17
18 RT_TASK intrtask, drawtask;
19 RTIME ticks[TICKS+1];
20 RTIME tocks[TICKS+1];
21
22 void add_tick(RTIME *t, RTIME tnew)
23 {
24 unsigned int i = 0;
25 t[TICKS] = 0;
26 for(i=TICKS-1; i>0; i--){
27 t[i] = t[i-1];
28 t[TICKS] += t[i];
29 }
30 t[0] = tnew;
31 t[TICKS] = t[TICKS]/TICKS;
32 }
33
34 void taskd(void *arg)
35 {
36 RTIME time = *(RTIME *)arg;
37 rt_printf("Time to draw=%.2fms\n", time/1000/1000.0);
38 RTIME step = time/MAXX;
39 rt_printf("Every x has %.2fms\n", step/1000/1000.0);
40 }
41
42 void taski(void *arg)
43 {
44 //Register as interrupt handler
45 RT_INTR intr;
46 rt_intr_create(&intr, NULL, LPT1IRQ, 0);
47 rt_printf("Interrupt created\n");
48
49 //Initialize and declare the timer variables
50 RTIME tick = rt_timer_read();
51 RTIME tock;
52 RTIME period;
53 while(1){
54 //Wait for tick (long stretch)
55 rt_intr_wait(&intr, TM_INFINITE);
56 tock = rt_timer_read();
57 add_tick(ticks, rt_timer_read()-tick);
58
59 // Tocks are the short stretches
60 if(tocks[TICKS] < ticks[TICKS]){
61 // sleep until the arm is most left
62 rt_task_sleep(tocks[TICKS]/2);
63 rt_task_create(&drawtask, NULL, 0, 50, 0);
64 period = ticks[TICKS]/2+tocks[TICKS]/2;
65 rt_task_start(&drawtask, &taskd, &period);
66 rt_printf("tocks is the short stretch\n");
67 }
68
69 //Wait for tock (shorter stretch)
70 rt_intr_wait(&intr, TM_INFINITE);
71 tick = rt_timer_read();
72 add_tick(tocks, rt_timer_read()-tock);
73
74 //Long stretch
75 if(ticks[TICKS] < tocks[TICKS]){
76 // sleep until the arm is most left
77 rt_task_sleep(ticks[TICKS]/2);
78 rt_task_create(&drawtask, NULL, 0, 50, 0);
79 period = tocks[TICKS]/2+ticks[TICKS]/2;
80 rt_task_start(&drawtask, &taskd, &period);
81 rt_printf("ticks is the short stretch\n");
82 }
83
84 //Print average
85 //rt_printf("avgtick: %lluns, avgtock: %lluns, avgticktock: %lluns\n",
86 // ticks[TICKS], tocks[TICKS], (ticks[TICKS]+tocks[TICKS])/2);
87 }
88 }
89
90 int main(int argc, char* argv[])
91 {
92 rt_print_auto_init(1);
93 mlockall(MCL_CURRENT | MCL_FUTURE);
94
95 // Get permission to write to parallel port
96 ioperm(0x37A, 1, 1);
97 ioperm(0x378, 1, 1);
98 outb(inb(0x37A) | 0x10, 0x37A);
99
100 rt_task_create(&intrtask, NULL, 0, 50, 0);
101 rt_task_start(&intrtask, &taski, 0);
102
103 pause();
104 }