-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpico.ino
391 lines (330 loc) · 12.8 KB
/
pico.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
#include <Wire.h>
#include <Adafruit_SSD1306.h>
//-----------------------------------------------
Adafruit_SSD1306 display(128, 64, &Wire, -1);
//-----------------------------------------------
#define CLK 19
#define DT 20
#define SW 21
//-----------------------------------------------
int flowMinutes = 0; // Total flow minutes
int menuIndex = 0; // 0 for UP, 1 for DOWN, 2 for Reset
String menuOptions[3] = {"UP", "DOWN", "Reset"}; // Label reset option as "Reset"
unsigned long lastActivityTime = 0; // For inactivity detection
const unsigned long inactivityLimit = 3 * 60000; // 3 minutes in milliseconds
enum State { MENU, COUNTING_UP, COUNTING_DOWN, SELECTING_DOWN_DURATION, IDLE };
State currentState = MENU;
int countdownValue = 20; // Default value for countdown
int initialCountdownValue = 20; // Store the countdown value when selected
unsigned long previousMillis = 0; // For counting logic
int elapsedMinutes = 0;
bool isCounting = false;
unsigned long buttonDebounceTime = 0;
const unsigned long buttonDebounceDelay = 800; // Debounce delay
// Rotary encoder debounce variables
unsigned long lastRotaryTime = 0;
const unsigned long rotaryDebounceDelay = 150; // Faster debounce for rotary encoder
// IDLE mode extended behavior
const unsigned long displayOffTimeLimit = 30 * 60000; // 30 minutes in milliseconds
unsigned long idleStartTime = 0; // Track when IDLE mode starts
bool displayOff = false; // Track if the display is off
//=========================================================
void setup() {
initHardware();
initDisplay();
updateDisplay();
Serial.println("Setup complete, starting loop...");
}
//=========================================================
void loop() {
unsigned long currentMillis = millis();
// Handle rotary encoder input
handleRotaryInput();
// Handle button presses and states
handleButtonPresses(currentMillis);
// Handle counting logic
handleCounting(currentMillis);
// Handle inactivity
handleInactivity(currentMillis);
}
//=========================================================
// Initialize hardware pins and serial communication
void initHardware() {
pinMode(CLK, INPUT_PULLUP);
pinMode(DT, INPUT_PULLUP);
pinMode(SW, INPUT_PULLUP);
Serial.begin(9600);
}
//=========================================================
// Initialize the OLED display
void initDisplay() {
if (!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
Serial.println(F("SSD1306 allocation failed"));
for (;;);
}
display.clearDisplay();
Serial.println("Display initialized.");
}
//=========================================================
// Update the OLED display with the current state
void updateDisplay() {
display.setTextColor(WHITE);
display.clearDisplay();
// Display top row
String topRowText;
if (currentState == COUNTING_UP) {
topRowText = "Focus! \x18"; // Focus with upward triangle for counting UP
} else if (currentState == COUNTING_DOWN) {
topRowText = "Focus! \x19"; // Focus with downward triangle for counting DOWN
} else {
topRowText = "Flow: " + String(flowMinutes); // Display total flow minutes when not counting
}
int topRowTextWidth = topRowText.length() * 12; // TextSize 2, so 12 pixels per char
int topRowX = (128 - topRowTextWidth) / 2; // Center the text on the top row
display.setTextSize(2); // Larger size for top row
display.setCursor(topRowX, 0); // Centered on top row
display.print(topRowText);
// Display main row (menu or counting values)
String mainRowText;
if (currentState == MENU) {
mainRowText = menuOptions[menuIndex]; // Display UP, DOWN, or Reset in the menu
} else if (currentState == COUNTING_UP) {
mainRowText = String(elapsedMinutes); // Display counting up minutes
} else if (currentState == COUNTING_DOWN || currentState == SELECTING_DOWN_DURATION) {
mainRowText = String(countdownValue); // Display countdown minutes
} else if (currentState == IDLE) {
mainRowText = "IDLE?";
}
int mainRowTextWidth = mainRowText.length() * 24; // TextSize 4, so 24 pixels per char
int mainRowX = (128 - mainRowTextWidth) / 2; // Calculate centered X position
display.setTextSize(4); // Larger size for main row
display.setCursor(mainRowX, 30); // Centered on main row
display.print(mainRowText);
display.display(); // Show the updated display
}
//=========================================================
// Detect button presses with debounce logic
bool buttonPressed() {
if (digitalRead(SW) == LOW && (millis() - buttonDebounceTime > buttonDebounceDelay)) {
buttonDebounceTime = millis(); // Debounce
lastActivityTime = millis(); // Reset inactivity timer
return true;
}
return false;
}
//=========================================================
// Handle button presses and manage state transitions
void handleButtonPresses(unsigned long currentMillis) {
if (!buttonPressed()) return;
switch (currentState) {
case MENU:
if (menuIndex == 0) { // UP selected
startCountingUp();
} else if (menuIndex == 1) { // DOWN selected
startSelectingDownDuration();
} else if (menuIndex == 2) { // Reset selected
resetFlowMinutes(); // Reset the total focus time to 0
}
break;
case SELECTING_DOWN_DURATION:
confirmCountdownSelection();
break;
case COUNTING_UP:
stopCountingUp();
break;
case COUNTING_DOWN:
stopCountingDown();
break;
}
updateDisplay();
}
//=========================================================
// Start counting up
void startCountingUp() {
currentState = COUNTING_UP;
elapsedMinutes = 0;
isCounting = true;
lastActivityTime = millis(); // Reset inactivity timer
Serial.println("Counting UP started.");
}
//=========================================================
// Start selecting the countdown duration
void startSelectingDownDuration() {
currentState = SELECTING_DOWN_DURATION;
countdownValue = 20;
lastActivityTime = millis(); // Reset inactivity timer
Serial.println("Selecting DOWN duration.");
}
//=========================================================
// Confirm countdown selection and start counting down
void confirmCountdownSelection() {
initialCountdownValue = countdownValue;
currentState = COUNTING_DOWN;
isCounting = true;
lastActivityTime = millis(); // Reset inactivity timer
Serial.print("Counting DOWN started with "); Serial.print(countdownValue); Serial.println(" minutes.");
}
//=========================================================
// Stop counting up and return to menu
void stopCountingUp() {
flowMinutes += elapsedMinutes;
successAnimation();
currentState = MENU;
isCounting = false;
Serial.println("Counting UP stopped. Returning to MENU.");
}
//=========================================================
// Stop counting down and return to menu
void stopCountingDown() {
flowMinutes += (initialCountdownValue - countdownValue);
successAnimation();
currentState = MENU;
isCounting = false;
Serial.println("Counting DOWN stopped. Returning to MENU.");
}
//=========================================================
// Reset the total flow minutes counter to 0
void resetFlowMinutes() {
flowMinutes = 0;
Serial.println("Flow minutes reset to 0.");
updateDisplay(); // Update the display to show the reset value
}
//=========================================================
// Handle counting up or down logic
void handleCounting(unsigned long currentMillis) {
if (!isCounting || (currentMillis - previousMillis < 60000)) return;
previousMillis = currentMillis;
if (currentState == COUNTING_UP) {
elapsedMinutes++;
updateDisplay();
Serial.print("Counting UP: "); Serial.println(elapsedMinutes);
} else if (currentState == COUNTING_DOWN) {
countdownValue--;
if (countdownValue <= 0) {
flowMinutes += initialCountdownValue;
successAnimation();
currentState = MENU;
isCounting = false;
Serial.println("Countdown finished, returning to MENU.");
}
updateDisplay();
Serial.print("Counting DOWN: "); Serial.println(countdownValue);
}
}
//=========================================================
// Success animation when a session ends
void successAnimation() {
display.clearDisplay();
int centerX = 64, centerY = 32;
for (int radius = 2; radius <= 30; radius += 2) {
display.drawCircle(centerX, centerY, radius, WHITE);
display.display();
delay(100);
if (radius % 4 == 0) {
display.clearDisplay();
display.display();
delay(2);
}
}
display.clearDisplay();
display.setTextSize(2);
display.setCursor(20, 20);
display.print("SUCCESS!");
display.display();
delay(1000);
display.clearDisplay();
display.display();
}
//=========================================================
// Rotary Encoder Rotation Detection
int getRotation() {
static int previousCLK = digitalRead(CLK);
int currentCLK = digitalRead(CLK);
if (currentCLK == LOW && previousCLK == HIGH && (millis() - lastRotaryTime > rotaryDebounceDelay)) {
lastRotaryTime = millis(); // Debounce
int DTValue = digitalRead(DT); // Read DT to determine direction
previousCLK = currentCLK; // Update previous CLK for next iteration
return (DTValue != currentCLK) ? 1 : -1; // Clockwise or counterclockwise
}
previousCLK = currentCLK;
return 0; // No rotation
}
//=========================================================
// Handle rotary input for menu and countdown selection
void handleRotaryInput() {
int rotation = getRotation();
if (rotation == 0) return; // No rotation detected
lastActivityTime = millis(); // Reset inactivity timer on any valid rotation
Serial.print(millis()); // Print the current time in milliseconds
Serial.print(" - Rotation detected, activity timer reset. Rotation: ");
Serial.println(rotation);
if (currentState == MENU) {
menuIndex = (menuIndex + rotation + 3) % 3; // Update for 3 menu options: UP, DOWN, Reset
updateDisplay();
Serial.print(millis()); // Print the current time in milliseconds
Serial.print(" - Menu option: "); Serial.println(menuOptions[menuIndex]);
} else if (currentState == SELECTING_DOWN_DURATION) {
countdownValue = max(1, countdownValue + rotation);
updateDisplay();
Serial.print(millis()); // Print the current time in milliseconds
Serial.print(" - Countdown value: "); Serial.println(countdownValue);
}
}
//=========================================================
// Handle inactivity and switch to IDLE if necessary
void handleInactivity(unsigned long currentMillis) {
// Comment out frequent serial prints to improve performance
/*
Serial.print(millis());
Serial.print(" - Current time (millis): ");
Serial.println(currentMillis);
Serial.print(millis());
Serial.print(" - Last activity time (millis): ");
Serial.println(lastActivityTime);
*/
// Make sure the subtraction does not cause an overflow/underflow
if (currentMillis >= lastActivityTime) {
unsigned long timeSinceLastActivity = currentMillis - lastActivityTime;
/*
Serial.print(millis());
Serial.print(" - Time since last activity (ms): ");
Serial.println(timeSinceLastActivity);
*/
// Check if the user is in the MENU or selecting countdown duration mode
if ((currentState == MENU || currentState == SELECTING_DOWN_DURATION) &&
(timeSinceLastActivity > inactivityLimit)) {
if (currentState != IDLE) {
currentState = IDLE;
idleStartTime = millis(); // Record when IDLE mode starts
updateDisplay();
Serial.print(millis()); // Print the current time in milliseconds
Serial.println(" - IDLE state entered due to inactivity.");
}
}
} else {
// Comment out warning to reduce unnecessary serial prints
// Serial.println(" - Warning: currentMillis is less than lastActivityTime!");
}
// Check if the user has been in IDLE for more than 30 minutes and turn off the display
if (currentState == IDLE && !displayOff && (currentMillis - idleStartTime > displayOffTimeLimit)) {
displayOff = true;
display.ssd1306_command(SSD1306_DISPLAYOFF); // Turn off the display
Serial.print(millis()); // Print the current time in milliseconds
Serial.println(" - Display turned off after 30 minutes of IDLE.");
}
// Exit IDLE if any rotary or button action happens
if (currentState == IDLE && (getRotation() != 0 || buttonPressed())) {
currentState = MENU;
lastActivityTime = millis(); // Reset inactivity timer upon exiting IDLE
// Turn the display back on if it was off
if (displayOff) {
display.ssd1306_command(SSD1306_DISPLAYON);
displayOff = false;
Serial.print(millis()); // Print the current time in milliseconds
Serial.println(" - Display turned back on.");
}
updateDisplay();
Serial.print(millis()); // Print the current time in milliseconds
Serial.println(" - Exiting IDLE mode. Back to MENU.");
}
}