-
Notifications
You must be signed in to change notification settings - Fork 0
/
DS3231_emu_exp.ino
3338 lines (2953 loc) · 101 KB
/
DS3231_emu_exp.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
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
// DS3231_emu_exp
//
// Merger of DS3231_emulator and DS3231_explorer
//
// The emulator maintains a PPS timer and emulates the DS3231 logic.
// The explorer displays its state and allows control via CLI.
// For now, we disable the I2C delegate serving of the emulator, since we also need I2C mastery to drive the display.
//
// dpwe@google.com 2023-01-14
// Explorer Command set:
// A - read aging offset register
// Ann - Set aging offset register
// Bx - Enable (x=1) / Disable (x=0) sqwv output on battery power
// Cx - Enable (x=1) / Disable (x=0) the 32 kHz output
// D - Display all registers
// Ex - Enable (x=1) / Disable (x=0) clock oscillator when on battery
// Gx - Enable/disable auto-clock-sync on GPS lock.
// Ix - Enable alarm interrupt outputs on sqwv pin (x=1) / Enable sqwv frequency output (x=0)
// Jnnn - Write DAC output value (0..4095)
// K - Save DAC value to EEPROM.
// L - Read Alarm 1
// Lx - Enable (x=1) / Disable (x=0) Alarm 1
// Lss - Set Alarm 1 for every minute at seconds SS
// Lmmss - Set Alarm 1 for every hour at min/sec MM:SS
// Lhhmmss - Set Alarm 1 for every day at time HH:MM:SS
// LWhhmmss - Set Alarm 1 for every week on dow W (Sunday = 1) at HH:MM:SS
// LDDhhmmss - Set Alarm 1 for every month on date DD at HH:MM:SS
// M - Read Alarm 2
// Mx - Enable (x=1) / Disable (x=0) Alarm 2
// Mmm - Set Alarm 2 for every hour at minutes mm
// Mhhmm - Set Alarm 2 for every day at time hh:mm
// MWhhmm - Set Alarm 2 for every week on dow W (Sunday = 1) at hh:mm
// MDDhhmm - Set Alarm 2 for every month on date DD at hh:mm
// Onn - Set backlight brightness (0..255)
// Px - Enable (x=1) / Disable (x=0) continuous polling of current time.
// Q - Read the sqwv frequency
// Qx - Set sqwv frequency : x=0 -> 1 Hz / x=1 -> 1024 Hz / x=2 -> 4096 Hz / x=3 -> 8192 Hz
// R - Reset the Oscillator Stop Flag
// Sx - Enable (x=1) / Disable (x=0) clock read on SQWV interrupt (on D3).
// T - Report most recent temp measurement
// T1 - Initiate a new temperature conversion
// Vxxx - Set predelay trim in us. Larger = sync earlier.
// Xnnn - Set/read display sleep timeout secs. 0=no display sleep.
// Y - sync to GPS
// Z - Read date/time
// ZYYYYMMDDhhmmss - Set date/time
// Emulator design:
// Arduino as I2C Secondary emulates behavior of DS3231 RTC
// including alarms and 1Hz SQWV output on SQWV_PIN
// but no 32 kHz output nor other SQWV frequencies.
// Aging is currently interpreted as ppb but limited to
// 8 bits signed, so max -128ppb/+127ppb.
//
// Wiring:
// RP2040 Pico/alt Feather RP2040 ESP32 Feather
// 10MHz in GP7 D11 GP11 D11 GP11
// I2C server SDA GP16/4 I2C0SDA A4 GP24 A4 GP14
// I2C server SCL GP17/5 I2C0SCL A5 GP25 A5 GP8
// RTC PPS out GP13+GP25 D13 GP13 D13 GP13
// GPS PPS in GP8/6 A2 GP28 A2 GP16
// GPS Serial in GP5/9 UART1RX RX GP1 RX GP2
// I2C display SDA GP2 I2C1SDA SDA GP2 (built-in)
// I2C display SCL GP3 I2C1SCL SCL GP3 (built-in)
// ST7920 LCD RST GP16
// ST7920 LCD CS/RS GP17 GP0
// ST7920 LCD SCLK GP18(+6) GP18+6 (192x64)
// ST7920 LCD MOSI GP19 GP19
// Backlight GP28 GP20 (built-in GP45)
// BTN A GP20 GP9 GP9 press: long press: sleep display
// BTN B GP21 GP8 GP6 press: inc trim long press: ?save trim to eeprom
// BTN C GP22 GP7 GP5 press: dec trim long press: sync to GPS
//
// DESIGN
//
// For greatest accuracy, the RTC state needs to update as soon as possible
// after a "tick" event, either from internal or external hardware timers.
// To avoid processing delay, we precompute the state *at the next second*
// and set up a "double buffered" set of registered. Then, when the "tick"
// interrupt occurs, we switch the register pointer to the precomputed set,
// and update the output pin (as appropriate). Then, back in the foreground
// loop, we notice that the time has changed, and set up for the next tick.
//
// Any configuration change (writing to registers) triggers a recompute of
// the next-tick state.
//
// The synchronization to the hardware timer is reset when the seconds
// register is written (only).
//
// Note, registers can be written "at any time" by i2c transactions. In
// theory this can affect derived state, for instance alarm trigger state.
// We have to avoid race conditions where registers are modified, but then
// a tick causes a double-buffer swap before the new register values are
// propagated to the setup for the next tick.
//
// dpwe@google.com 2022-12-31
#include <SPI.h>
#include <Wire.h> // https://www.arduino.cc/en/Reference/Wire
#include <RTClib.h> // Adafruit; defines RTC_DS3231
#ifdef ARDUINO_ARCH_RP2040
#ifdef PIN_NEOPIXEL // i.e., this is a Feather RP2040
#define FEATHER_RP2040
//#define DISPLAY_SH1107 // 128x(64,128) mono OLED in Feather stack
//#define FEATHER_OLED // Different address than ext OLED.
#define DISPLAY_ST7920 // {128,192}x64 green-yellow LCD matrix
//#define SCREEN_WIDTH 128
#define SCREEN_WIDTH 192
#define EXT_I2C Wire1 // Feather has reorderd the I2C pins to look right to Arduino users
#define INT_I2C Wire
// Initialize Aging specifically for Feather RP2040 with mini Connor OCXO
#define INITIAL_DS3231_AGING 35
#else
#define MY_PICO_RP2040
#define DISPLAY_ST7920 // {128,192}x64 green-yellow LCD matrix
#define EXT_I2C Wire // Pico still has "native" I2C numbering
#define INT_I2C Wire1
// Is Serial2 on 8/9 or 4/5?
// VCOCXO does not neeed aging trim
#define SLOW_CONNOR_OCXO // The super small Connor OCXO needs a different base count.
#ifdef SLOW_CONNOR_OCXO
#define INITIAL_DS3231_AGING -50
#define SCREEN_WIDTH 192
#else
// VCOCXO does not neeed aging trim
#define INITIAL_DS3231_AGING 0
// VCOCXO has narrow LCD
#define SCREEN_WIDTH 128
// .. and uses 8/9 for serial etc.
#define PICO_SERIAL_89
#endif
#endif
// Hardware limits mean that pins 24 and 25 (A4 and A5, favored choice for ext_i2)
// must be assigned to I2C0 aka Wire on RP2040. Wire1 is only for pins 2(n+1), 2(n+1)+1.
const int ext_sda_pin = 24;
const int ext_scl_pin = 25;
const int int_sda_pin = 2;
const int int_scl_pin = 3;
#else // ESP32-S3
const int ext_sda_pin = A4;
const int ext_scl_pin = A5;
#define EXT_I2C Wire1
#define INT_I2C Wire
#define DISPLAY_ST7789 // Built-in display on ESP32-S3 TFT
//#define DISPLAY_SSD1351 // Exernal 128x128 RGB TFT
#endif
// ------------- General Display ---------------
#include <Adafruit_GFX.h>
#ifdef DISPLAY_SSD1351
#warning "DISPLAY_SSD1351 128x128 OLED"
#include <Adafruit_SSD1351.h>
// Screen dimensions
#define SCREEN_WIDTH 128
#define SCREEN_HEIGHT 128 // Change this to 96 for 1.27" OLED.
#define SIZE_1X
// Hardware SPI pins
// (for UNO thats sclk = 13 and sid = 11) and pin 10 must be
// an output.
#define DC_PIN 4
#define CS_PIN 5
#define RST_PIN 6
Adafruit_SSD1351 display = Adafruit_SSD1351(SCREEN_WIDTH, SCREEN_HEIGHT, &SPI, CS_PIN, DC_PIN, RST_PIN);
// Color definitions
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
#endif
#ifdef DISPLAY_ST7789
#warning "DISPLAY_ST7789 Built-in display on ESP32-S3 TFT"
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#define SCREEN_WIDTH 240
#define SCREEN_HEIGHT 135 // Change this to 96 for 1.27" OLED.
#define SIZE_2X // All text double-size
// Use dedicated hardware SPI pins
Adafruit_ST7789 display = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);
#define DISPLAY_BACKLIGHT
const int backlightPin = TFT_BACKLITE; // PWM output to drive dimmable backlight
#define WHITE ST77XX_WHITE
#define BLACK ST77XX_BLACK
#define BLUE ST77XX_BLUE
#define RED ST77XX_RED
#define GREEN ST77XX_GREEN
#define CYAN ST77XX_CYAN
#define MAGENTA ST77XX_MAGENTA
#define YELLOW ST77XX_YELLOW
#endif
#ifdef DISPLAY_SH1107
#warning "DISPLAY_SH1107 - Adafruit OLED either feather 64x128 or external 128x128"
#include <Adafruit_SH110X.h>
// SH1107 needs display.display() after drawing
#define DISPLAY_DISPLAY_CMD
#ifdef FEATHER_OLED
const int display_address = 0x3C;
#define SCREEN_HEIGHT 64
#else // standalone OLED
const int display_address = 0x3D;
#define SCREEN_HEIGHT 128
#endif
#define SCREEN_WIDTH 128
#define SIZE_1X
Adafruit_SH1107 display = Adafruit_SH1107(SCREEN_HEIGHT, SCREEN_WIDTH, &INT_I2C);
// Monochrome, all colors are white
#define WHITE SH110X_WHITE
#define BLACK SH110X_BLACK
#define MONOCHROME
#endif
#ifdef DISPLAY_ST7920
#warning "DISPLAY_ST7920 - 3 inch 128x64 LCD matrix"
#include "ST7920_GFX_Library.h"
// ST7920 needs display.display() after drawing
#define DISPLAY_DISPLAY_CMD
#define SIZE_1X
// Backlight pin
#define DISPLAY_BACKLIGHT
#ifdef FEATHER_RP2040
// Pins specific to the Feather RP2040 build
const int backlightPin = 20;
const int CS_PIN = 0;
#else
// Pins on RP2040 Pico build
const int backlightPin = 28;
const int CS_PIN = 17;
#endif
// Default hardware SPI pins - SCLK GP18 / MOSI GP19 / RST GP16
//const int MOSI_PIN = 19;
const int CLK1_PIN = 18;
// 192-column ST7920 uses a second CLK pin
const int CLK2_PIN = 6;
// ST7920 LCD RST [ora]
// ST7920 LCD CS (RS) [ylw] GP17
// ST7920 LCD SCLK1(E1) [blu] GP18
// ST7920 LCD SCLK2(E2) [pur] GP06
// ST7920 LCD MOSI (RW) [grn] GP19,,,,,,,,,,,,,,,
#define SCREEN_HEIGHT 64
//ST7920 display(CS_PIN);
#if SCREEN_WIDTH == 192
ST7920_192 display(CS_PIN, CLK1_PIN, CLK2_PIN);
#else
ST7920 display(CS_PIN);
#endif
// Monochrome, all colors are white
// "Black" means background
#define BLACK 0
#define WHITE 1
#define MONOCHROME
#endif
#ifdef MONOCHROME
#define BLUE WHITE
#define RED WHITE
#define GREEN WHITE
#define CYAN WHITE
#define MAGENTA WHITE
#define YELLOW WHITE
#endif
#ifdef SIZE_1X
// 1x size
#define SMALL_SIZE 1
#define LARGE_SIZE 2
#define ROW_H 8
#define CHAR_W 6
#else
// 2x size
#define SMALL_SIZE 2
#define LARGE_SIZE 4
#define ROW_H 16
#define CHAR_W 12
#endif
uint8_t backlight_brightness = 255;
void set_backlight(int val) {
Serial.print("set_backlight:");
Serial.println(val);
#ifdef DISPLAY_BACKLIGHT
analogWrite(backlightPin, val);
#endif
}
void setup_backlight(int initial_val) {
#ifdef DISPLAY_BACKLIGHT
pinMode(backlightPin, OUTPUT);
#endif
Serial.print("setup_backlight:");
Serial.println(initial_val);
set_backlight(initial_val);
}
void setup_display(void) {
#ifdef DISPLAY_SSD1351
display.begin();
#endif
// turn on backlite
setup_backlight(backlight_brightness);
#ifdef DISPLAY_ST7789
display.init(135, 240); // Init ST7789 240x135
display.setRotation(3);
#endif
#ifdef DISPLAY_SH1107
display.begin(display_address, true);
display.display(); // Splashscreen
delay(1000);
display.clearDisplay();
display.display();
display.setRotation(1);
#endif
#ifdef DISPLAY_ST7920
display.begin();
display.setTextSize(1);
display.setTextColor(BLACK);
display.setCursor(0, 0);
display.println("Hello, world!");
display.display();
delay(2000);
#endif
display.fillScreen(BLACK);
// text display
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0, 0);
display.print("DS3231_emu_exp");
}
// ------ DS3231 internal status display ------
const char *CONTROL_SHORTNAMES[8] = { "E", "Q", "C", "R", "R", "I", "E", "E" };
const char *STATUS_SHORTNAMES[8] = { "O", "x", "x", "x", "3", "B", "F", "F" };
void print_bits_tft(uint16_t x, uint16_t y, uint8_t val, const char *names[8], uint16_t fgcolor = WHITE, uint16_t bgcolor = BLACK) {
// Print a bit set using an array of names.
uint8_t mask = 0x80; // Start with top bit.
display.setTextColor(fgcolor, bgcolor);
display.setCursor(x, y);
for (uint8_t bit = 0; bit < 8; ++bit) {
bool bitval = ((val & mask) > 0);
// "Set" bits are printed in reverse video.
if (bitval) display.setTextColor(bgcolor, fgcolor);
display.print(names[bit]);
uint16_t w = strlen(names[bit]) * CHAR_W;
if (bitval) {
display.setTextColor(fgcolor, bgcolor);
// Also add top/left edges
display.drawFastHLine(x - 1, y - 1, w + 1, fgcolor);
display.drawFastVLine(x - 1, y, ROW_H, fgcolor);
} else {
// Need to undraw the overbar.
display.drawFastHLine(x - 1, y - 1, w + 1, bgcolor);
}
x += w;
display.print(" ");
x += CHAR_W;
mask >>= 1;
}
}
void getAlarmModeTemplateString(char *s, uint8_t mode, uint8_t alarm_num) {
if (alarm_num == 2) {
// Map alarm2 modes to alarm1 modes by shifting left.
mode <<= 1;
}
// Templates are for alarm2; for alarm1, we'll add seconds later.
switch (mode) {
case DS3231_A1_PerSecond:
case DS3231_A1_Second:
strcpy(s, "--- --:--");
break;
case DS3231_A1_Minute:
strcpy(s, "--- --:mm");
break;
case DS3231_A1_Hour:
strcpy(s, "--- hh:mm");
break;
case DS3231_A1_Date:
strcpy(s, "-DD hh:mm");
break;
case DS3231_A1_Day: // Day of the week.
strcpy(s, "DDD hh:mm");
break;
}
if (alarm_num == 1) {
// Need to append seconds field.
char *s_end = s + strlen(s);
if (mode == DS3231_A1_PerSecond) {
strcpy(s_end, ":--");
} else {
strcpy(s_end, ":ss");
}
}
}
// Updated by main loop, used to display here.
long int skew_us = 0;
long int last_skew_us = 0;
// Holds skew_us immediately after GPS sync.
long int initial_skew_us = 0;
void display_skew_us(long int skew_microseconds, int x, int y); // forward dec.
// Set when GPS syncs the time.
time_t last_gps_sync_unixtime = 0;
// Last time the GPS transitioned to available.
DateTime last_gps_uptime;
// Last time the GPS transitioned to not available.
DateTime last_gps_downtime;
void itoa2(int num, char *s, int base = 10) {
// Convert a number to '00\0' or similar.
#define DTOA(d) ((d < 10) ? ('0' + d) : ('A' + d - 10))
*s++ = DTOA(num / base);
*s++ = DTOA(num % base);
*s++ = '\0';
}
bool gps_active = false;
long int secs_since_sync = 0;
const long int settle_time_since_sync = 20; // wait this long before tracking difference in ppb.
void draw_ppb(int x, int y, bool break_line=false) {
// Print the PPB to the current text cursor position.
// Figure PPB
// if long int is 32 bit, then largest value is ~2e9, so numerator will overflow
// when skew_us is 2e4 or 20 ms.
if (secs_since_sync > settle_time_since_sync) {
char s[12];
long int ppb_times_100 = (100000L * (skew_us - initial_skew_us)) / (secs_since_sync - settle_time_since_sync);
display.setCursor(x * CHAR_W, y * ROW_H);
display.print("ppb: ");
if (break_line)
display.setCursor(x * CHAR_W, (y + 1) * ROW_H);
if (ppb_times_100 < 0) {
display.print("-");
ppb_times_100 = -ppb_times_100;
}
int ppb = ppb_times_100 / 100;
itoa(ppb, s, 10);
display.print(s);
if (ppb < 1000) {
display.print(".");
itoa2(ppb_times_100 % 100, s);
s[1 + (ppb < 100)] = '\0';
display.print(s);
}
}
}
void display_gps_status(int x, int y, bool include_ppb=false) {
// GPS status
display.setFont();
display.setCursor((x + 1) * CHAR_W, y * ROW_H);
if (gps_active) {
display.setTextColor(BLACK, GREEN);
display.print("GPS");
display.drawLine((x + 1) * CHAR_W - 1, y * ROW_H, (x + 1) * CHAR_W - 1, (y + 1) * ROW_H - 1, WHITE);
} else {
display.setTextColor(GREEN, BLACK);
display.print(" ");
display.drawLine(x * CHAR_W - 1, y * ROW_H, x * CHAR_W - 1, (y + 1) * ROW_H - 1, BLACK);
}
display_skew_us(skew_us, x, y + 1);
if (include_ppb)
draw_ppb(x, y + 3, /*break_line=*/true);
}
void ds3231_display(class RTC_DS3231 &ds3231, const char *clock_name, bool display_detail) {
// Graphical display of DS3231 state for 16x8 display:
// HHHH::MMMM::SSSS
// HHHH::MMMM::SSSS (double-size)
// 2023-01-06
// A1: --- --:03:00 (only enabled shown)
// A2: Wed 03:59
// C: E Q C R R I E E (reverse video for set bits)
// S: O x x x 3 B F F
// A:-127 T:23.25C
// Regs would be 19 bytes ~ 57 chars incl. spaces
// SS MM HH OO DD MM YY - maybe 7 bytes with N extra pixels between bytes = 7x12 + Nx6 - 96 for N=2, 120 for N=6 (128 is 21 chars @6)
// S1 M1 H1 D1 M2 H2 D2
// CC SS AO TH TL
#ifdef DISPLAY_DISPLAY_CMD
display.clearDisplay();
#endif
display.setFont();
// Clock source identifier tag
//display.setTextSize(SMALL_SIZE);
//display.setTextColor(RED, BLACK);
//display.setCursor(17 * CHAR_W, 0);
//display.print(clock_name);
display_gps_status(16, 0);
// Time, double size.
display.setTextSize(LARGE_SIZE);
display.setTextColor(WHITE, BLACK);
display.setCursor(0, 0);
char s[32];
strcpy(s, "hh:mm:ss");
ds3231.now().toString(s);
display.print(s);
//Serial.println(s);
// Date, normal size, yellow.
display.setTextSize(SMALL_SIZE);
display.setTextColor(YELLOW, BLACK);
display.setCursor(0, 2 * ROW_H);
strcpy(s, "YYYY-MM-DD");
ds3231.now().toString(s);
display.print(s);
if (display_detail) {
// Alarm1
display.setTextColor(CYAN, BLACK);
display.setCursor(0, 3 * ROW_H);
strcpy(s, "A1: ");
getAlarmModeTemplateString(s + 4, (uint8_t)ds3231.getAlarm1Mode(), /* alarm_num */ 1);
ds3231.getAlarm1().toString(s);
display.print(s);
// Alarm2
display.setTextColor(BLUE, BLACK);
display.setCursor(0, 4 * ROW_H);
strcpy(s, "A2: ");
getAlarmModeTemplateString(s + 4, (uint8_t)ds3231.getAlarm2Mode(), /* alarm_num */ 2);
ds3231.getAlarm2().toString(s);
display.print(s);
// Control byte
display.setTextColor(GREEN, BLACK);
display.setCursor(0, 5 * ROW_H);
strcpy(s, "C: ");
display.print(s);
print_bits_tft(3 * CHAR_W, 5 * ROW_H, ds3231.getControlReg(), CONTROL_SHORTNAMES, GREEN, BLACK);
// Status byte
display.setTextColor(YELLOW, BLACK);
display.setCursor(0, 6 * ROW_H);
strcpy(s, "S: ");
display.print(s);
print_bits_tft(3 * CHAR_W, 6 * ROW_H, ds3231.getStatusReg(), STATUS_SHORTNAMES, YELLOW, BLACK);
// Aging offset
display.setTextColor(RED, BLACK);
display.setCursor(0, 7 * ROW_H);
strcpy(s, "A:");
itoa(ds3231.getAging(), s + 2, 10);
display.print(s);
display.print(" ");
// Temp
display.setTextColor(MAGENTA, BLACK);
display.setCursor(8 * CHAR_W, 7 * ROW_H);
strcpy(s, "T:");
float t = ds3231.getTemperature();
itoa(int(t), s + 2, 10);
char *s_end = s + strlen(s);
*s_end = '.';
itoa(100 * (t - int(t)), s_end + 1, 10);
display.print(s);
display.print(" ");
} else {
// Display time of last GPS sync
display.setCursor(0, 4 * ROW_H);
display.print("GPSSync: ");
char *sp = s;
if (last_gps_sync_unixtime > 0) {
TimeSpan since_sync = TimeSpan(secs_since_sync);
itoa(since_sync.days(), sp, 10);
sp += strlen(sp);
*sp++ = 'd';
*sp++ = ' ';
itoa(since_sync.hours(), sp, 10);
sp += strlen(sp);
*sp++ = ':';
itoa2(since_sync.minutes(), sp);
sp += 2;
*sp++ = ':';
itoa2(since_sync.seconds(), sp);
sp += 2;
*sp = '\0';
display.print(s);
draw_ppb(0, 5);
} else {
display.print("none");
}
display.setCursor(0, 6 * ROW_H);
display.print("GPSUp: ");
if (!last_gps_uptime.secondstime()) {
strcpy(s, "none");
} else {
strcpy(s, "MM-DD hh:mm:ss");
last_gps_uptime.toString(s);
}
display.print(s);
display.setCursor(0, 7 * ROW_H);
display.print("GPSDn: ");
if (!last_gps_downtime.secondstime()) {
strcpy(s, "none");
} else {
strcpy(s, "MM-DD hh:mm:ss");
last_gps_downtime.toString(s);
}
display.print(s);
}
#ifdef DISPLAY_DISPLAY_CMD
display.display();
#endif
}
// ------ Skew re: GPS display -----
//bool gps_active = false;
int delta_skew_us = 0;
void display_skew_us(long int skew_microseconds, int x, int y) {
//Serial.print("display_skew_us=");
//Serial.println(skew_microseconds);
char s[5]; // "-0.0\0"
long int skew_milliseconds;
if (skew_microseconds < 0L) {
s[0] = '-';
skew_microseconds = -skew_microseconds;
} else {
s[0] = '+';
}
if (skew_microseconds >= 9950L) {
// format as +/-123
skew_microseconds += 500; // rounding
skew_milliseconds = skew_microseconds / 1000L;
if (skew_milliseconds > 999L) {
skew_milliseconds = 999L;
}
itoa(skew_milliseconds, s + 1, 10);
} else if (skew_microseconds >= 995L) {
// format as +/-0.1
// Round up
skew_microseconds += 50L; // rounding
skew_milliseconds = skew_microseconds / 1000L;
s[1] = '0' + skew_milliseconds;
s[2] = '.';
s[3] = '0' + ((skew_microseconds / 100L) - (10 * skew_milliseconds));
} else {
// format as +/-.99
// Round up
skew_microseconds += 5L; // rounding
s[1] = '.';
s[2] = '0' + (skew_microseconds / 100L);
s[3] = '0' + ((skew_microseconds / 10L) % 10L);
}
if (s[2] == '\0') {
s[2] = ' ';
s[3] = '\0';
}
if (s[3] == '\0') {
s[3] = ' ';
s[4] = '\0';
}
s[4] = '\0';
// Now actually display it.
display.setTextColor(RED, BLACK);
display.setCursor(x * CHAR_W, y * ROW_H);
if (gps_active) {
display.print(s);
// Add latest delta too
s[0] = 30; // "Up filled triangle" character.
itoa(delta_skew_us, s + 1, 10);
display.setCursor(x * CHAR_W, (y + 1) * ROW_H);
display.print(s);
} else {
display.print(" ");
}
}
// -------------- Time --------------------
#define CLOCK_ADDRESS 0x68
#define DS3231_TIME 0x00 ///< Time register
#define DS3231_ALARM1 0x07 ///< Alarm 1 register
#define DS3231_ALARM2 0x0B ///< Alarm 2 register
#define DS3231_CONTROL 0x0E ///< Control register
#define DS3231_STATUSREG 0x0F ///< Status register
#define DS3231_AGING 0x10 ///< Aging offset register
#define DS3231_TEMPERATUREREG 0x11 ///< Temperature register (high byte - low byte is at 0x12), 10-bit \
///< temperature value
#define time_t uint32_t
RTC_DS3231 ds3231;
void sprint_datetime(const DateTime &dt, char *s) {
// s must have 20 bytes.
strcpy(s, "YYYY-MM-DD hh:mm:ss");
dt.toString(s);
}
void serial_print_time(const DateTime &dt) {
char s[20];
sprint_datetime(dt, s);
Serial.println(s);
}
// Predeclare
time_t ds3231_unixtime(void);
// getExternalTime is declared to expect a function returning a (signed) long int.
//time_t
#ifdef ARDUINO_ARCH_RP2040 // Needed to compile on M4
long
#endif
long int RTC_utc_get(void) {
return ds3231_unixtime();
}
void RTC_set_time(const DateTime &dt) {
// Set the DS3231 time.
Serial.print("Set RTC: ");
serial_print_time(dt);
ds3231.adjust(dt);
// Resync TimeLib
//setTime(ds3231_unixtime());
}
// ---- Misc formatting -----
void print2Digits(int digits, int base = 10) {
// Print a 2-digit value with a leading zero if needed.
if (digits < base)
Serial.print('0');
Serial.print(digits, base);
}
void sprint_bits(uint8_t val, const char *names[8], char *s) {
// Print a bit set using an array of names.
uint8_t mask = 0x80; // Actually start with top bit.
for (uint8_t bit = 0; bit < 8; ++bit) {
strcpy(s, names[bit]);
s += strlen(s);
*s++ = ':';
*s++ = '0' + ((val & mask) > 0);
*s++ = ' ';
*s++ = ' ';
*s = '\0';
mask >>= 1;
}
}
void print_bits(uint8_t val, const char *names[8]) {
// Print bits. Special case for to_display.
char s[70];
sprint_bits(val, names, s);
Serial.print(s);
}
// ----- Encode/decode DS3231 registers ---------
#define BCDTODEC(x) ((x)-6 * ((x) >> 4))
DateTime ds3231_regs_to_datetime(uint8_t *regs) {
// Format the 7 byte DS3231 time registers to a DateTime obj.
uint8_t secs = BCDTODEC(regs[0]);
uint8_t mins = BCDTODEC(regs[1]);
uint8_t hours = BCDTODEC(regs[2]);
uint8_t dow = BCDTODEC(regs[3]); // 1-7.
uint8_t day = BCDTODEC(regs[4]); // 1-31
uint8_t month = BCDTODEC(regs[5] & 0x7F); // 1-12
uint16_t year = 2000 + ((regs[5] & 0x80) ? 100 : 0) + BCDTODEC(regs[6]);
return DateTime(year, month, day, hours, mins, secs);
}
void sprint_alarm(uint8_t *regs, char *s, bool has_secs = true) {
// Format the status of alarm from the 4 bytes (0 + 3 bytes for Alarm 2).
int8_t secs = 0;
int8_t mode = 0;
// Alarm2 has no seconds register, so only try to access if it's there.
if (has_secs) {
secs = BCDTODEC(regs[0] & 0x7F);
mode = regs[0] >> 7;
} else {
// Alarm2, take seconds register as zero.
regs -= 1; // To make remaining registers line up.
}
int8_t mins = BCDTODEC(regs[1] & 0x7F);
int8_t hours = BCDTODEC(regs[2] & 0x7F);
int8_t days = BCDTODEC(regs[3] & 0x3F);
mode |= ((regs[3] >> 7) << 3) | ((regs[2] >> 7) << 2) | ((regs[1] >> 7) << 1);
int8_t daynotdate = (regs[3] >> 6) & 0x01;
switch (mode) {
case 0xF:
strcpy(s, "every sec");
break;
case 0xE:
strcpy(s, "every min at ");
break;
case 0xC:
strcpy(s, "every hour at ");
break;
case 0x8:
strcpy(s, "every day at ");
break;
case 0x0:
if (daynotdate) {
// Day of week.
const char dow[] = "SunMonTueWedThuFriSat";
strcpy(s, "every ");
s += strlen(s);
days %= 7; // Ensure 0 (Sun) to 6 (Sat).
for (int i = 0; i < 3; ++i) {
s[i] = dow[3 * days + i];
}
s[3] = '\0';
s += strlen(s);
strcpy(s, " at ");
} else {
// Day of month.
strcpy(s, "on the ");
s += strlen(s);
itoa2(days, s);
s += strlen(s);
strcpy(s, " of each month at ");
}
break;
default:
Serial.print("Invalid Alarm mode 0x");
Serial.println(mode, HEX);
break;
}
s += strlen(s);
// Print the actual time.
switch (mode) {
case 0x0:
case 0x8:
// Print hours.
itoa2(hours, s);
s += strlen(s);
// Fall through.
case 0xC:
// Print mins.
*s++ = ':';
itoa2(mins, s);
s += strlen(s);
// Fall through.
case 0xE:
// Print secs.
*s++ = ':';
itoa2(secs, s);
s += strlen(s);
break;
default:
break;
}
}
void print_registers(uint8_t *registers) {
// Display all 19 hex registers.
Serial.print("Regs: ");
for (int i = 0; i < 19; ++i) {
if (registers[i] < 16) Serial.print("0");
Serial.print(registers[i], HEX);
Serial.print(" ");
}
Serial.println("");
}
const char *CONTROL_NAMES[8] = { "#EO", "BSQ", "CNV", "RS2", "RS1", "INT", "A2E", "A1E" };
const char *STATUS_NAMES[8] = { "OSF", " x ", " x ", " x ", "EN3", "BSY", "A2F", "A1F" };
void print_registers_fancy(uint8_t *registers) {
// Decode the entire state of the DS3231 to the terminal.
// registers[19] is return from ds3231.getRegisters().
// Print date/time.
char s[70]; // Needed for longest sprint_bits.
Serial.print("Time:");
for (int i = 0; i < 7; ++i) {
Serial.print(' ');
print2Digits(registers[i], 16);
}
// Format the date/time
DateTime dt;
dt = ds3231_regs_to_datetime(registers);
sprint_datetime(dt, s);
Serial.print(": ");
Serial.println(s);
Serial.print("Alarm1: ");
for (int i = 7; i < 11; ++i) {
Serial.print(' ');
print2Digits(registers[i], 16);
}
// Format the alarm.
sprint_alarm(registers + 7, s);
Serial.print(": ");
Serial.println(s);
Serial.print("Alarm2: ");
for (int i = 11; i < 14; ++i) {
Serial.print(' ');
print2Digits(registers[i], 16);
}
// Format Alarm2 (no seconds register).
sprint_alarm(registers + 11, s, /* has seconds= */ false);
Serial.print(": ");
Serial.println(s);
Serial.print("Contrl: ");
print2Digits(registers[14], 16);
Serial.print(": ");
print_bits(registers[14], CONTROL_NAMES);
Serial.println("");
Serial.print("Status: ");
print2Digits(registers[15], 16);
Serial.print(": ");
print_bits(registers[15], STATUS_NAMES);
Serial.println("");
Serial.print("Aging: ");
print2Digits(registers[16], 16);
Serial.print(": ");
Serial.println(*(int8_t *)(registers + 16), 10);
Serial.print("Temp: ");
print2Digits(registers[17], 16);
Serial.print(' ');
print2Digits(registers[18], 16);
Serial.print(": ");
Serial.print(*(int8_t *)(registers + 17), 10);
Serial.print('.');
Serial.println(25 * (registers[18] >> 6), 10);
Serial.println("");
}
// ---- MCP4728 DAC / EEPROM output ------
#include <Adafruit_MCP4728.h>
// DAC is on internal (main) I2C
#define DAC_I2C INT_I2C
// DAC I2C address
#define DAC_I2C_ADDRESS 0x60
Adafruit_MCP4728 mcp;
bool dac_available = false;
int dac_a_value = 1500; // about 20 counts per (us per 100s, or 1e-8), so 2 counts = 1ppb
// for 10^7-1 counts per sec, DAC=1892 ended up 1.3 ppb fast
// for 10^7 counts per sec, DAC=2056 was pretty flat
// 2024-01-28: After 40h, clock reported -2.20 ppb (i.e, fast), so reduced DAC to 2053.
// so ? 164 DAC for 100 ppb
void dac_set_value(int value) {
if (dac_available) {
dac_a_value = value;
mcp.setChannelValue(MCP4728_CHANNEL_A, dac_a_value);
}
}
void dac_save_to_eeprom(void) {
if (dac_available) {
mcp.saveToEEPROM();
}
}