Repository navigation
Expand file tree
/
Copy pathtikiv3.ino
More file actions
1896 lines (1567 loc) · 61.1 KB
/
Copy pathtikiv3.ino
File metadata and controls
1896 lines (1567 loc) · 61.1 KB
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2023 Phil B. for Adafruit Industries
// SPDX-License-Identifier: MIT
#include <Adafruit_seesaw.h>
#include <seesaw_neopixel.h>
#include <esp_now.h>
#include <WiFi.h>
#include <driver/rtc_io.h>
// NeoPixel configuration
#define PIN 15
#define TOTAL_PIXELS 36
// Sleep mode configuration
#define BUTTON_HOLD_TIME 2000 // 2 seconds to trigger sleep/wake
// Tiki Face Sections
#define BOTTOM_TEETH_START 0
#define BOTTOM_TEETH_END 11
#define TOP_TEETH_START 12
#define TOP_TEETH_END 23
#define LEFT_EYE_START 24
#define LEFT_EYE_END 29
#define RIGHT_EYE_START 30
#define RIGHT_EYE_END 35
// ANO Rotary Encoder
#define ANO_ADDR 0x49 // Corrected address per Adafruit docs
#define ANO_SWITCH 1 // center switch
#define ANO_UP 2 // up button
#define ANO_DOWN 4 // down button
#define ANO_LEFT 3 // left button
#define ANO_RIGHT 5 // right button
// Define patterns
#define NUM_PATTERNS 5
// ESP-Now broadcast configuration
uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // Broadcast to all ESP devices
#define SYNC_INTERVAL 1000 // Sync every second
#define ESP_NOW_MAX_RETRIES 3 // Number of retries for ESP-NOW initialization
// Data structure for ESP-Now synchronization
typedef struct sync_message {
uint32_t timestamp; // Seconds since boot (for leader election)
uint32_t animTime; // Animation time in ms (for sync)
uint8_t pattern; // Current pattern number
uint8_t brightness; // Current brightness
uint8_t colorOffset; // Current color offset
uint8_t customColor; // Whether custom color is active
} sync_message;
// Create a sync structure for sending and receiving data
sync_message syncData;
// Flag to track if ESP-NOW is properly initialized
bool espNowInitialized = false;
seesaw_NeoPixel strip =
seesaw_NeoPixel(TOTAL_PIXELS, PIN, NEO_GRB + NEO_KHZ800);
Adafruit_seesaw ano = Adafruit_seesaw();
// Global variables
int currentPattern = 0;
int brightness = 255; // 0-255 (start at maximum brightness)
int colorPosition = 0; // 0-255 for color wheel position
int baseColorOffset = 0; // Starting color offset for the current pattern
int targetColorOffset = 0; // Target color offset when rotating the encoder
bool useCustomColor = false; // Flag to indicate custom color should be used
bool initialColorSet = false; // Flag to track if we've set an initial random color
uint32_t lastPatternChange = 0;
uint32_t lastButtonCheck = 0;
uint32_t lastUpdate = 0;
uint32_t animationStep = 0;
uint32_t lastEyeBlink = 0; // For occasional random eye blinks
uint32_t nextBlinkTime = 0; // When to do the next blink
bool isBlinking = false; // Currently in a blink animation
uint8_t blinkState = 0; // State of the blink animation
uint32_t startBlinkMs_ = 0; // Start time for the current blink (for easing calculation)
uint32_t endBlinkMs_ = 0; // End time for the current blink (for easing calculation)
float blinkFadeBrightness_ = 1.0; // Brightness factor for eye blinks (1.0 = full brightness, 0.0 = off)
bool anoAvailable = false;
// ESP-Now synchronization variables
uint32_t lastSyncTime = 0;
uint32_t bootTime = 0;
uint32_t lastChangeTime = 0; // Track when last change happened
bool syncPending = false;
bool fastSyncMode = false; // Track if we're in fast sync mode
int32_t animationOffset = 0; // Offset to maintain animation continuity when bootTime changes
uint32_t sharedTime = 0; // Synchronized time for animations
// Sleep mode variables
uint32_t buttonPressStartTime = 0;
bool buttonLongPressInProgress = false;
bool inSleepMode = false;
bool longPressHandled = false; // Track if the long press was already handled
// Callback when data is sent
void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
// Packet send callback (logging removed for normal operation)
// Only log errors
if (status != ESP_NOW_SEND_SUCCESS) {
Serial.println("ERROR: ESP-NOW packet delivery failed");
}
}
// Callback when data is received
void OnDataRecv(const esp_now_recv_info_t *recv_info, const uint8_t *incomingData, int len) {
// Don't process syncs while in sleep mode - sleep is sticky per-device
if (inSleepMode) {
return;
}
sync_message *incomingSync = (sync_message *)incomingData;
// Compare received timestamp with local time
uint32_t localTimestamp = (millis() - bootTime) / 1000;
// If received timestamp is ahead of ours, adopt their settings
if (incomingSync->timestamp > localTimestamp) {
// Use a single millis() call for consistency
uint32_t now = millis();
uint32_t oldSharedTime = sharedTime;
// Set sync flag to true so we won't broadcast immediately
syncPending = true;
// Update our local timestamp to match received one
// Add a small millisecond offset to account for transmission delay
bootTime = now - (incomingSync->timestamp * 1000 + 50);
// Sync animation time: adjust our offset so sharedTime matches sender's
// This ensures: sharedTime = now - bootTime - animationOffset = animTime
animationOffset = (int32_t)(now - bootTime) - (int32_t)incomingSync->animTime;
// Log adoption with animation timing info
Serial.print("ADOPT: t=");
Serial.print(incomingSync->timestamp);
Serial.print(" anim=");
Serial.print(incomingSync->animTime);
Serial.print(" old=");
Serial.print(oldSharedTime);
Serial.print(" new=");
Serial.println(now - bootTime - animationOffset);
bool stateChanged = false;
// Update pattern
if (currentPattern != incomingSync->pattern) {
currentPattern = incomingSync->pattern;
animationStep = 0;
lastPatternChange = millis();
stateChanged = true;
}
// Update brightness
if (brightness != incomingSync->brightness) {
brightness = incomingSync->brightness;
strip.setBrightness(brightness);
stateChanged = true;
}
// Update color offset - immediately set both base and target to received value
if (colorPosition != incomingSync->colorOffset || useCustomColor != (incomingSync->customColor != 0)) {
Serial.print("Updating color from ");
Serial.print(colorPosition);
Serial.print(" to ");
Serial.println(incomingSync->colorOffset);
// Set both base and target color to the exact same value to avoid transition
baseColorOffset = incomingSync->colorOffset;
targetColorOffset = incomingSync->colorOffset;
colorPosition = incomingSync->colorOffset;
useCustomColor = (incomingSync->customColor != 0);
stateChanged = true;
}
// If state changed, enter fast sync mode
if (stateChanged) {
lastChangeTime = millis();
fastSyncMode = true;
// Fast sync mode enabled (logging removed for normal operation)
}
}
}
void setup() {
Serial.begin(115200);
delay(1000); // Give serial a moment to initialize
Serial.println("Starting tiki LED sculpture");
// Set boot time
bootTime = millis();
// Initialize NeoPixels first
Serial.println("Initializing NeoPixel seesaw...");
if (!strip.begin(0x60)) {
Serial.println("NeoPixel seesaw not found! Check connections.");
// Blink the built-in LED to indicate error
pinMode(LED_BUILTIN, OUTPUT);
while (1) {
digitalWrite(LED_BUILTIN, HIGH);
delay(300);
digitalWrite(LED_BUILTIN, LOW);
delay(300);
}
}
Serial.println("NeoPixel seesaw started OK!");
strip.setBrightness(brightness);
strip.show(); // Initialize all pixels to 'off'
// Initialize ANO encoder (optional)
Serial.println("Attempting to connect to ANO encoder...");
// Try to connect to ANO
for (int attempt = 0; attempt < 3; attempt++) {
delay(100);
anoAvailable = ano.begin(ANO_ADDR);
if (anoAvailable) {
uint16_t pid = ano.getVersion();
Serial.print("Seesaw found Product ID: ");
Serial.println(pid, HEX);
// Accept the actual product ID (0x4A97) we're seeing
if (pid != 0x4A97) {
Serial.println("Unknown product ID for seesaw device");
anoAvailable = false;
} else {
Serial.println("Recognized compatible seesaw device");
break;
}
}
Serial.println("ANO connection attempt failed, retrying...");
}
if (!anoAvailable) {
Serial.println("ANO seesaw not found! Will run without input controls.");
Serial.println("Cycling through patterns automatically.");
} else {
Serial.println("ANO seesaw started OK!");
// Configure ANO buttons
ano.pinMode(ANO_SWITCH, INPUT_PULLUP);
ano.pinMode(ANO_UP, INPUT_PULLUP);
ano.pinMode(ANO_DOWN, INPUT_PULLUP);
ano.pinMode(ANO_LEFT, INPUT_PULLUP);
ano.pinMode(ANO_RIGHT, INPUT_PULLUP);
// Initialize encoder
ano.setEncoderPosition(0);
// Enable encoder interrupt
ano.enableEncoderInterrupt();
Serial.println("ANO controls ready!");
}
// Initialize the pattern change timer
lastPatternChange = millis();
lastUpdate = millis();
// Initialize ESP-Now with retry logic
WiFi.mode(WIFI_STA);
// Get MAC for debugging
Serial.print("ESP32 MAC Address: ");
Serial.println(WiFi.macAddress());
// Try to initialize ESP-Now with multiple attempts
espNowInitialized = false;
for (int attempt = 0; attempt < ESP_NOW_MAX_RETRIES; attempt++) {
Serial.print("ESP-NOW initialization attempt ");
Serial.print(attempt + 1);
Serial.print(" of ");
Serial.println(ESP_NOW_MAX_RETRIES);
// Reset WiFi first
WiFi.disconnect();
delay(10);
WiFi.mode(WIFI_STA);
delay(10);
// Try to initialize ESP-Now
esp_err_t result = esp_now_init();
if (result == ESP_OK) {
Serial.println("ESP-Now initialized successfully");
espNowInitialized = true;
// Register the send callback
esp_now_register_send_cb(OnDataSent);
// Register peer (broadcast address)
esp_now_peer_info_t peerInfo;
memset(&peerInfo, 0, sizeof(peerInfo)); // Zero out the structure first
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
// Delete any existing peer first
esp_now_del_peer(broadcastAddress);
// Add peer
if (esp_now_add_peer(&peerInfo) != ESP_OK) {
Serial.println("Failed to add peer");
espNowInitialized = false;
} else {
// Register for a callback function that will be called when data is received
esp_now_register_recv_cb(OnDataRecv);
Serial.println("ESP-Now peer added and callbacks registered");
break; // Success - exit retry loop
}
} else {
Serial.print("ESP-Now init failed with error: ");
Serial.println(result);
// Try de-initializing before retrying
esp_now_deinit();
delay(200); // Brief pause before retry
}
}
if (espNowInitialized) {
Serial.println("ESP-Now initialized and ready");
} else {
Serial.println("Failed to initialize ESP-Now after multiple attempts");
Serial.println("Will continue without sync capabilities");
}
// Initialize blink timing with robust values
uint32_t currentTime = millis();
nextBlinkTime = currentTime + random(2000, 10000); // Initial blink delay between 2-10 seconds
blinkFadeBrightness_ = 1.0; // Start with eyes fully visible
// Make sure all blink state variables are initialized correctly
blinkState = 0;
isBlinking = false;
startBlinkMs_ = currentTime;
endBlinkMs_ = currentTime + 300;
lastEyeBlink = currentTime;
// Blink initialization complete
Serial.println("Setup complete - starting animation");
}
// Function to enter sleep mode (just turn off LEDs)
void enterSleepMode() {
Serial.println("Entering sleep mode...");
Serial.println("anoAvailable=" + String(anoAvailable));
// Turn off all LEDs
for (int i = 0; i < TOTAL_PIXELS; i++) {
strip.setPixelColor(i, 0);
}
strip.show();
// Set sleep mode flag
inSleepMode = true;
Serial.println("LEDs turned off, device in sleep mode");
}
// Function to wake from sleep mode
void wakeFromSleepMode() {
Serial.println("Waking from sleep mode...");
Serial.println("anoAvailable=" + String(anoAvailable));
// Clear sleep mode flag
inSleepMode = false;
// Reset animation timers
uint32_t now = millis();
lastUpdate = now;
animationStep = 0;
// Reset blink state to avoid any issues from sleep mode
isBlinking = false;
blinkState = 0;
blinkFadeBrightness_ = 1.0f;
startBlinkMs_ = now;
endBlinkMs_ = now + 300;
nextBlinkTime = now + random(2000, 10000); // Random delay after wake
Serial.println("Wake from sleep - reset blink state and scheduled next blink");
// Randomize the pattern on wake (optional - gives visual feedback that device is awake)
currentPattern = random(NUM_PATTERNS);
// Randomize color for immediate visual feedback
colorPosition = random(256);
targetColorOffset = colorPosition;
baseColorOffset = colorPosition;
useCustomColor = true;
// Show a quick flash of light to confirm wake
for (int i = 0; i < TOTAL_PIXELS; i++) {
strip.setPixelColor(i, strip.Color(255, 255, 255));
}
strip.show();
delay(50);
Serial.println("Device awake, resuming normal operation");
}
// Function to advance timestamp while preserving animation phase
void advanceTimestamp() {
uint32_t now = millis();
// Save old sharedTime before changing bootTime
uint32_t oldSharedTime = now - bootTime - animationOffset;
// Advance our time by 2 seconds
uint32_t currentTime = (now - bootTime) / 1000;
bootTime = now - ((currentTime + 2) * 1000);
// Adjust animationOffset to keep sharedTime continuous
uint32_t newRawTime = now - bootTime;
animationOffset = newRawTime - oldSharedTime;
}
// Function to broadcast the current state to all other tikis
void broadcastSync() {
// Skip if ESP-NOW was not successfully initialized
if (!espNowInitialized) {
// Only log this periodically to avoid spam
static uint32_t lastLogTime = 0;
uint32_t currentMillis = millis();
if (currentMillis - lastLogTime > 10000) { // Log every 10 seconds
Serial.println("Broadcast skipped - ESP-NOW not initialized");
lastLogTime = currentMillis;
}
return;
}
// Prepare the data packet
memset(&syncData, 0, sizeof(syncData)); // Clear any stale data
// Calculate seconds since boot
syncData.timestamp = (millis() - bootTime) / 1000;
syncData.pattern = currentPattern;
syncData.brightness = brightness;
// Send the colorPosition/targetOffset rather than baseColorOffset
// This ensures we sync to the target color immediately
syncData.colorOffset = useCustomColor ? colorPosition : baseColorOffset;
syncData.animTime = sharedTime;
syncData.customColor = useCustomColor ? 1 : 0;
// Color broadcasting (logging removed for normal operation)
// Try to re-initialize ESP-NOW if not working
static uint8_t errorCount = 0;
// Send message via ESP-Now with retry on failure
esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *)&syncData, sizeof(syncData));
if (result == ESP_OK) {
// Success (logging removed for normal operation)
errorCount = 0; // Reset error count on success
} else {
Serial.print("Error sending broadcast: ");
Serial.println(result);
// Count errors and attempt to reinitialize if persistent
errorCount++;
if (errorCount >= 5) {
Serial.println("Multiple broadcast failures - attempting to reinitialize ESP-NOW");
// Try to reinitialize ESP-NOW
esp_now_deinit();
delay(100);
if (esp_now_init() == ESP_OK) {
// Re-register callbacks and peer
esp_now_register_send_cb(OnDataSent);
esp_now_register_recv_cb(OnDataRecv);
esp_now_peer_info_t peerInfo;
memset(&peerInfo, 0, sizeof(peerInfo));
memcpy(peerInfo.peer_addr, broadcastAddress, 6);
peerInfo.channel = 0;
peerInfo.encrypt = false;
esp_now_del_peer(broadcastAddress);
esp_now_add_peer(&peerInfo);
Serial.println("ESP-NOW reinitialized");
errorCount = 0;
} else {
Serial.println("ESP-NOW reinitialization failed");
}
}
}
}
void loop() {
uint32_t currentMillis = millis();
// Calculate shared time for synchronized animations (with offset for continuity)
sharedTime = currentMillis - bootTime - animationOffset;
// Always check buttons even in sleep mode (to detect wake button press)
if (anoAvailable && currentMillis - lastButtonCheck >= 50) {
// Only print initial sleep status once
static bool sleepStatusPrinted = false;
if (inSleepMode && !sleepStatusPrinted) {
Serial.println("Device in sleep mode, checking buttons for wake signals");
sleepStatusPrinted = true;
} else if (!inSleepMode) {
// Reset the flag when out of sleep mode
sleepStatusPrinted = false;
}
checkInputs();
lastButtonCheck = currentMillis;
}
// Calculate these values regardless of sleep state
uint32_t secondsSinceBoot = (currentMillis - bootTime) / 1000;
uint32_t millisInCurrentSecond = (currentMillis - bootTime) % 1000;
uint32_t syncInterval = fastSyncMode ? 100 : SYNC_INTERVAL;
// If in sleep mode, skip animation and patterns but still process buttons and ESP-Now
if (inSleepMode) {
// Check if we should still be in fast sync mode
if (fastSyncMode && currentMillis - lastChangeTime > 30000) {
fastSyncMode = false;
// Exiting fast sync mode (logging removed for normal operation)
}
// Reset syncPending flag if we've moved to the next opportunity
if (syncPending && espNowInitialized) {
if (fastSyncMode && currentMillis - lastSyncTime >= syncInterval) {
syncPending = false;
} else if (!fastSyncMode && millisInCurrentSecond >= 100) {
syncPending = false;
}
}
// Return early - we've processed button inputs and ESP-Now sync flags
return;
}
// Only non-sleeping devices continue here
// Check if it's time to sync with other devices
// Check if we should still be in fast sync mode
if (fastSyncMode && currentMillis - lastChangeTime > 30000) {
fastSyncMode = false;
// Exiting fast sync mode (logging removed for normal operation)
}
// We already calculated syncInterval above
// Only try to sync if ESP-NOW is initialized
if (espNowInitialized) {
// If in fast mode, sync frequently
if (fastSyncMode) {
if (currentMillis - lastSyncTime >= syncInterval && !syncPending) {
// Fast sync (logging removed for normal operation)
broadcastSync();
lastSyncTime = currentMillis;
}
}
// In normal mode, sync on the second mark for better synchronization
else if (millisInCurrentSecond < 100 && currentMillis - lastSyncTime >= syncInterval && !syncPending) {
// Normal sync (logging removed for normal operation)
broadcastSync();
lastSyncTime = currentMillis;
}
} else {
// ESP-NOW not available, still update the sync time to avoid spam
if (currentMillis - lastSyncTime >= 10000) { // Only check every 10 seconds
lastSyncTime = currentMillis;
}
}
// Reset syncPending flag if we've moved to the next opportunity
if (syncPending) {
if (fastSyncMode && currentMillis - lastSyncTime >= syncInterval) {
syncPending = false;
} else if (!fastSyncMode && millisInCurrentSecond >= 100) {
syncPending = false;
}
}
// Auto-cycle patterns if ANO is not available
if (!anoAvailable &&
currentMillis - lastPatternChange >= 15000) { // Change every 15 seconds
currentPattern = (currentPattern + 1) % NUM_PATTERNS;
Serial.print("Auto-changing to pattern: ");
Serial.println(currentPattern);
animationStep = 0;
lastPatternChange = currentMillis;
}
// Update the base color offset smoothly if needed, but only for local changes
// Skip smooth transitions for synchronized values to maintain perfect color sync
if (baseColorOffset != targetColorOffset && !syncPending) {
// Gradually move towards target (faster when rotating encoder)
static uint32_t lastColorTransition = 0;
// Calculate distance between current and target
int distance = abs(targetColorOffset - baseColorOffset);
if (distance > 128) {
// If we need to go more than halfway around the wheel, use the shorter path
distance = 256 - distance;
}
// For very small distances, just snap to the target value
if (distance <= 3) {
baseColorOffset = targetColorOffset;
Serial.println("Snapping to target color (close enough)");
}
// Otherwise use smooth transitions for user experience
else {
// Use variable speed based on distance - faster when further from target
int transitionDelay = 25; // Much faster than before (was 80ms)
if (currentMillis - lastColorTransition >= transitionDelay) {
// Step size also varies with distance
int stepSize = 1;
if (distance > 60) stepSize = 3; // Faster movement when far away
else if (distance > 30) stepSize = 2;
// Make the move using shortest path
if (baseColorOffset < targetColorOffset) {
if (targetColorOffset - baseColorOffset > 128) {
// Go backward (shorter)
baseColorOffset = (baseColorOffset - stepSize) % 256;
} else {
// Go forward
baseColorOffset = (baseColorOffset + stepSize) % 256;
}
} else if (baseColorOffset > targetColorOffset) {
if (baseColorOffset - targetColorOffset > 128) {
// Go forward (shorter)
baseColorOffset = (baseColorOffset + stepSize) % 256;
} else {
// Go backward
baseColorOffset = (baseColorOffset - stepSize) % 256;
}
}
// Wrap around color wheel
if (baseColorOffset >= 256) baseColorOffset = 0;
if (baseColorOffset < 0) baseColorOffset += 256;
lastColorTransition = currentMillis;
}
}
}
// Safety check to ensure we're in a clean state before starting a new blink
static uint32_t lastBlinkCompletionCheck = 0;
if (currentMillis - lastBlinkCompletionCheck > 200) { // Check every 200ms
lastBlinkCompletionCheck = currentMillis;
// If we think we're blinking but the end time is long past, something's wrong
if (isBlinking && currentMillis > endBlinkMs_ + 2000) {
Serial.println("RECOVERY: Detected stale blink state - forcing reset");
isBlinking = false;
blinkState = 0;
blinkFadeBrightness_ = 1.0f;
nextBlinkTime = currentMillis + random(2000, 10000);
}
}
// Check if we need to do a random eye blink in smooth patterns
if (!isBlinking && currentMillis >= nextBlinkTime) { // Allow blinking for all patterns
// Start a blink with clear state initialization
isBlinking = true;
blinkState = 0;
lastEyeBlink = currentMillis;
// Initialize the timing variables to avoid potential stale values
startBlinkMs_ = currentMillis;
endBlinkMs_ = currentMillis + 300;
blinkFadeBrightness_ = 1.0f;
}
// Run current pattern first
updatePattern(currentMillis);
// Handle eye blinking if needed
// Add safety check to avoid infinite loops or state corruption
static uint32_t lastBlinkCheck = 0;
// First, check for obviously invalid states that might cause infinite loops
if (isBlinking && (blinkState > 3 || startBlinkMs_ > currentMillis + 1000 ||
(endBlinkMs_ < startBlinkMs_) ||
(currentMillis > endBlinkMs_ + 10000))) {
Serial.println("ERROR: Invalid blink timing or state detected! Resetting");
isBlinking = false;
blinkState = 0;
blinkFadeBrightness_ = 1.0f;
nextBlinkTime = currentMillis + random(2000, 10000); // Random delay to recover
lastBlinkCheck = currentMillis;
}
// Then check if we need to handle the blink animation normally
else if (isBlinking) {
// Update the last check time
lastBlinkCheck = currentMillis;
// Process the blink animation
handleEyeBlink(currentMillis);
}
// End of main loop
}
void updatePattern(uint32_t currentMillis) {
// Set an initial random color if this is the first time running a pattern
if (!initialColorSet) {
// Generate a random color and set it as our custom color
colorPosition = random(256);
baseColorOffset = colorPosition;
targetColorOffset = colorPosition;
useCustomColor = true;
initialColorSet = true;
Serial.print("Setting initial random color: ");
Serial.println(colorPosition);
}
// Update animation based on the current pattern
switch (currentPattern) {
case 0:
// Fire eyes with custom color influence
fireEyesPatternCustom(currentMillis, 50);
break;
case 1:
// Gentle rainbow pattern with color subset (slowed down)
gentleRainbowTikiCustom(currentMillis, 60); // Was 30, now 60ms
break;
case 2:
// Smooth breathing with custom colors
breathingPatternCustom(currentMillis, 30);
break;
case 3:
// Gradient teeth pattern
gradientTeethPattern(currentMillis, 40);
break;
case 4:
// Color wave pattern
colorWavePattern(currentMillis, 30);
break;
default:
// Default to fire eyes
fireEyesPatternCustom(currentMillis, 50);
break;
}
}
void checkInputs() {
if (!anoAvailable) {
Serial.println("ANO not available, skipping input check");
return;
}
uint32_t now = millis();
// If in sleep mode, only log when buttons are actually pressed
if (inSleepMode) {
bool centerBtn = !ano.digitalRead(ANO_SWITCH);
// Only log when a button is actually pressed
if (centerBtn) {
Serial.println("Center button pressed while in sleep mode - preparing to wake");
}
}
// Read encoder for color control
int32_t encoderPosition = ano.getEncoderPosition();
static int32_t lastPosition = 0;
if (encoderPosition != lastPosition) {
int change = encoderPosition - lastPosition;
colorPosition = (colorPosition + change) % 256;
if (colorPosition < 0) colorPosition += 256;
Serial.print("Color position: ");
Serial.println(colorPosition);
lastPosition = encoderPosition;
// Set target color offset for smooth transition
targetColorOffset = colorPosition;
// Update base color offset immediately to avoid color sync issues
baseColorOffset = colorPosition;
// Set flag to use custom color
useCustomColor = true;
// Force our timestamp to advance so we become the master
// But only update once per 500ms to avoid flooding with updates during rapid rotation
static uint32_t lastEncoderUpdate = 0;
if (now - lastEncoderUpdate > 500) {
advanceTimestamp();
lastEncoderUpdate = now;
// Enter fast sync mode
fastSyncMode = true;
lastChangeTime = now;
// Fast sync mode enabled (logging removed for normal operation)
// Broadcast soon but not immediately (allow for more encoder turns)
lastSyncTime = now - 900; // Will broadcast in ~100ms
}
}
// Read buttons with debouncing
static bool lastButtons[5] = {false, false, false, false, false};
// Center button - randomize or sleep/wake
bool centerButton = !ano.digitalRead(ANO_SWITCH);
// Button just pressed (transition from not pressed to pressed)
if (centerButton && !lastButtons[0]) {
// Start tracking for potential long press for sleep/wake
buttonLongPressInProgress = true;
buttonPressStartTime = now;
Serial.println("Starting sleep/wake timer (inSleepMode=" + String(inSleepMode) + ")");
// If in sleep mode, wake up IMMEDIATELY on press, don't wait for release
if (inSleepMode) {
Serial.println("Center button pressed while sleeping - WAKING UP IMMEDIATELY");
wakeFromSleepMode();
// Reset long press handling
longPressHandled = false;
} else {
Serial.println("Center button pressed - randomizing immediately");
// Randomize pattern
currentPattern = random(NUM_PATTERNS);
// Randomize color - set all color values to the same value
colorPosition = random(256);
targetColorOffset = colorPosition;
baseColorOffset = colorPosition; // Set directly to the same value to avoid transition
// Enable custom color mode
useCustomColor = true;
// Reset animation
animationStep = 0;
lastUpdate = now;
// Schedule next random eye blink with safe values
// Always cancel any in-progress blink
isBlinking = false;
blinkState = 0;
blinkFadeBrightness_ = 1.0f;
// Set random delay for next blink after randomization
nextBlinkTime = now + random(2000, 10000);
// Reset blink timing variables
startBlinkMs_ = now;
endBlinkMs_ = now + 300;
// Random pattern blink reset (logging removed for normal operation)
Serial.print("Random pattern: ");
Serial.println(currentPattern);
Serial.print("Random color: ");
Serial.println(colorPosition);
Serial.print("Random brightness: ");
Serial.println(brightness);
lastPatternChange = now;
// Force our timestamp to advance so we become the master
advanceTimestamp();
// Enter fast sync mode
fastSyncMode = true;
lastChangeTime = now;
// Fast sync mode enabled (logging removed for normal operation)
// Reset sync time to broadcast the change immediately
lastSyncTime = 0;
}
}
// Track button hold time for sleep/wake functionality
// longPressHandled is now a global variable
if (centerButton) {
// Button pressed - new press or continued hold
if (!buttonLongPressInProgress) {
// This is a new button press (wasn't previously pressed)
buttonLongPressInProgress = true;
buttonPressStartTime = now;
longPressHandled = false; // Reset for new press
Serial.println("New button press detected, longPressHandled reset to false");
}
// Check if we've held long enough for sleep
if (buttonLongPressInProgress && !longPressHandled && (now - buttonPressStartTime >= BUTTON_HOLD_TIME)) {
Serial.println("Long press detected! (inSleepMode=" + String(inSleepMode) +
", buttonPressStartTime=" + String(buttonPressStartTime) +
", now=" + String(now) +
", delta=" + String(now - buttonPressStartTime) + ")");
// Mark this long press as handled (so we don't toggle again on release)
longPressHandled = true;
if (inSleepMode) {
// If already in sleep mode, wake up
wakeFromSleepMode();
} else {
// Enter sleep mode
enterSleepMode();
}
}
}
else if (buttonLongPressInProgress) {
// Button was released
Serial.println("Button released after " + String(now - buttonPressStartTime) +
"ms (longPressHandled=" + String(longPressHandled) +
", inSleepMode=" + String(inSleepMode) + ")");
buttonLongPressInProgress = false;
// Note: We no longer handle wake on release since we do it on press
// But reset the flag anyway
longPressHandled = false;
}
lastButtons[0] = centerButton;
// Up button - increase brightness
bool upButton = !ano.digitalRead(ANO_UP);
if (upButton && !lastButtons[1]) {
Serial.println("Up button pressed - increasing brightness");
brightness = constrain(brightness + 25, 10, 255);
strip.setBrightness(brightness);
Serial.print("Brightness: ");
Serial.println(brightness);
// Force our timestamp to advance so we become the master
advanceTimestamp();
// Enter fast sync mode
fastSyncMode = true;
lastChangeTime = now;
Serial.println("Entering fast sync mode");
// Reset sync time to broadcast the change immediately
lastSyncTime = 0;
}
lastButtons[1] = upButton;
// Down button - decrease brightness
bool downButton = !ano.digitalRead(ANO_DOWN);
if (downButton && !lastButtons[2]) {
Serial.println("Down button pressed - decreasing brightness");
brightness = constrain(brightness - 25, 10, 255);
strip.setBrightness(brightness);
Serial.print("Brightness: ");
Serial.println(brightness);
// Force our timestamp to advance so we become the master
advanceTimestamp();
// Enter fast sync mode
fastSyncMode = true;
lastChangeTime = now;
Serial.println("Entering fast sync mode");
// Reset sync time to broadcast the change immediately
lastSyncTime = 0;
}
lastButtons[2] = downButton;
// Left button - previous pattern
bool leftButton = !ano.digitalRead(ANO_LEFT);
if (leftButton && !lastButtons[3]) {
Serial.println("Left button pressed - previous pattern");
changePattern(-1);
}
lastButtons[3] = leftButton;
// Right button - next pattern
bool rightButton = !ano.digitalRead(ANO_RIGHT);
if (rightButton && !lastButtons[4]) {
Serial.println("Right button pressed - next pattern");
changePattern(1);
}
lastButtons[4] = rightButton;
}
void changePattern(int direction) {
uint32_t now = millis();
animationStep = 0;
lastUpdate = now;
currentPattern = (currentPattern + NUM_PATTERNS + direction) % NUM_PATTERNS;