1#include <LCD-I2C.h>
2LCD_I2C lcd(0x27, 16, 2);
3
4#define RIGHT true
5#define LEFT false
6
7const int leftButton = 4;
8const int rightButton = 3;
9const int limit = 2;
10const int Rpot = A6;
11const int Lpot = A7;
12
13volatile unsigned long NOW;
14volatile unsigned long THEN;
15
16volatile long Rtime;
17volatile long Ltime;
18
19volatile bool limitState;
20
21void setup() {
22 Serial.begin(9600);
23 pinMode(leftButton, INPUT);
24 pinMode(rightButton, INPUT);
25 pinMode(limit, INPUT);
26 pinMode(Rpot, INPUT);
27 pinMode(Lpot, INPUT);
28
29 attachInterrupt(digitalPinToInterrupt(limit), timeTrigger, CHANGE);
30
31 limitState = digitalRead(limit);
32
33 lcd.begin();
34 lcd.display();
35 lcd.backlight();
36}
37
38void reset() {
39 Rtime = 100 * 60 * map(analogRead(Rpot), 0, 1023, 300, 0);
40 Ltime = 100 * 60 * map(analogRead(Lpot), 0, 1023, 300, 0);
41 printTime();
42
43 return delay(500);
44}
45
46void timeTrigger() {
47 static unsigned long last_interrupt_time = 0;
48 unsigned long interrupt_time = millis();
49
50 if (interrupt_time - last_interrupt_time > 200) { limitState = !limitState; }
51
52 last_interrupt_time = interrupt_time;
53}
54
55long deduction() {
56 NOW = millis();
57 long elapsed = NOW - THEN;
58
59 THEN = NOW;
60
61 return elapsed;
62}
63
64void countDown() {
65 if (limitState == RIGHT) { Rtime -= deduction(); }
66 if (limitState == LEFT) { Ltime -= deduction(); }
67
68 Rtime = max(Rtime, 0);
69 Ltime = max(Ltime, 0);
70}
71
72void printTime() {
73
90
91 int r_total_s = Rtime / 1000;
92 int l_total_s = Ltime / 1000;
93
94 int r_time_m = r_total_s / 60;
95 int r_time_s = r_total_s % 60;
96
97 int l_time_m = l_total_s / 60;
98 int l_time_s = l_total_s % 60;
99
100
101
102 lcd.setCursor(0, 0);
103 lcd.print("00:00");
104
105 if (r_time_m < 10) {
106 lcd.setCursor(1, 0);
107 } else {
108 lcd.setCursor(0, 0);
109 }
110 lcd.print(r_time_m);
111
112 if (r_time_s < 10) {
113 lcd.setCursor(4, 0);
114 } else {
115 lcd.setCursor(3, 0);
116 }
117
118 lcd.print(r_time_s);
119
120
121 lcd.setCursor(11, 0);
122 lcd.print("00:00");
123
124 if (l_time_m < 10) {
125 lcd.setCursor(12, 0);
126 } else {
127 lcd.setCursor(11, 0);
128 }
129 lcd.print(l_time_m);
130
131 if (l_time_s < 10) {
132 lcd.setCursor(15, 0);
133 } else {
134 lcd.setCursor(14, 0);
135 }
136
137 lcd.print(l_time_s);
138}
139
140void start() {
141 THEN = millis();
142
143 while (Rtime > 0 && Ltime > 0) {
144 boolean shouldReset = digitalRead(leftButton) && digitalRead(rightButton);
145
146 if (shouldReset) { return reset(); }
147
148 countDown();
149
150 printTime();
151 }
152}
153
154void loop() {
155 if (digitalRead(leftButton)) { reset(); }
156
157 if (digitalRead(rightButton)) { start(); }
158}
jackcchen1
8 months ago
Looks great!