Add countdown
[hdmi-switcher.git] / main.c
1 #include <stdio.h>
2 #include <wiringPi.h>
3 #include <time.h>
4 #define COIN_BUTTON 7
5 #define CREDIT_EXTENSION 10
6
7 int expires = -1;
8 int one_second_ago = 0;
9
10 void init_gpio()
11 {
12 wiringPiSetup();
13 pinMode(COIN_BUTTON, INPUT);
14 pullUpDnControl(COIN_BUTTON, PUD_UP);
15 }
16
17 int now()
18 {
19 return (unsigned)time(NULL);
20 }
21
22 int time_over()
23 {
24 if(one_second_ago != now() && expires != -1)
25 {
26 printf("You have %d seconds remaining\n", expires - now());
27 one_second_ago = now();
28 }
29
30 if(expires == now())
31 {
32 printf("It's all ogre now\n");
33 expires = -1;
34 return 1;
35 }
36
37 return expires == -1;
38 }
39
40 int read_button()
41 {
42 if(digitalRead(COIN_BUTTON) == LOW)
43 {
44 printf("Nice! I just added %d to your time.\n", CREDIT_EXTENSION);
45
46 //Increment timer
47 if(expires == -1) //Initial credit, set the expiry to now plus time
48 {
49 expires = now() + CREDIT_EXTENSION;
50 } else { //expiry already set, simply extend by time
51 expires += CREDIT_EXTENSION;
52 }
53
54 //wait for button to be released
55 while(digitalRead(COIN_BUTTON) == LOW)
56 {
57 //I don't see this happening, but in principle if the button is held down
58 //It would be possible to stop the switch happening after time runs out
59 //So we must check for that here.
60 if(time_over())
61 break;
62
63 delay(10);
64 }
65
66 return 1;
67 }
68
69 return 0;
70 }
71
72 int main (void)
73 {
74 init_gpio();
75 printf ("Short pin 7 and 9 to increment timer.\n") ;
76
77 while(1)
78 {
79 read_button();
80 //I don't really need to call this here but I'm doing it to see output.
81 time_over();
82 delay(10);
83 }
84 }