-
Notifications
You must be signed in to change notification settings - Fork 4
/
GPS_Clock.c
1318 lines (1196 loc) · 44 KB
/
GPS_Clock.c
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
/*
GPS Clock
Copyright (C) 2016 Nicholas W. Sayer
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
// Fuse settings: lfuse=0xe2, hfuse=0xdf, efuse=0xff
// Hardware options:
// ---
// V2 hardware has the PPS going into the ICP pin instead of INT0
#define V2
// V3 has the PPS line going into ICP2 instead of ICP1 so !SS can be !D_CS
#define V3
// V3.1 has the two buttons moved to port A to make room for the crystal
// on pins B0 & B1.
#define V31
// Define this if your board uses an 12 MHz crystal instead of the RC oscillator
//#define XTAL
// !NEW_AMPM hardware has AM on the digit 7 DP and PM on the digit 6 DP
#define NEW_AMPM
// Older hardware doesn't have a tenth of a second digit
#define TENTH_DIGIT
// Older hardware doesn't have colons.
#define COLONS
// ---
#if (defined(V31) && !defined(V3))
#error V31 requires V3
#endif
#if (defined(XTAL) && !defined(V31))
#error XTAL requires V31
#endif
#if (defined(V3) && !defined(V2))
#error V3 requires V2
#endif
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <avr/io.h>
#include <avr/eeprom.h>
#include <avr/power.h>
#include <avr/wdt.h>
#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <util/atomic.h>
#ifdef XTAL
// 12 MHz.
#define F_CPU (12000000UL)
#else
// 8 MHz.
#define F_CPU (8000000UL)
#endif
#include <util/delay.h>
// UBRR?_VALUE macros defined here are used below in serial initialization in main()
#define BAUD 9600
#include <util/setbaud.h>
// Port A is used for the display SPI interface and serial.
// We don't need to config the serial pins - it's enough to
// just turn on the USART.
#define PORT_MAX PORTA
#ifdef V3
#define BIT_MAX_CS _BV(PORTA7)
#else
#define BIT_MAX_CS _BV(PORTA3)
#endif
// MOSI and SCK are taken care of by the SPI stuff, but must still
// have the DDR bits set to make them outputs.
#ifdef V3
#define DDR_BITS_A _BV(DDA7) | _BV(DDA4) | _BV(DDA6)
#else
#define DDR_BITS_A _BV(DDA3) | _BV(DDA4) | _BV(DDA6)
#endif
// The MAX6951 registers and their bits
#define MAX_REG_DEC_MODE 0x01
#define MAX_REG_INTENSITY 0x02
#define MAX_REG_SCAN_LIMIT 0x03
#define MAX_REG_CONFIG 0x04
#define MAX_REG_CONFIG_R _BV(5)
#define MAX_REG_CONFIG_T _BV(4)
#define MAX_REG_CONFIG_E _BV(3)
#define MAX_REG_CONFIG_B _BV(2)
#define MAX_REG_CONFIG_S _BV(0)
#define MAX_REG_TEST 0x07
// P0 and P1 are planes - used when blinking is turned on
// or the mask with the digit number 0-7. On the hardware, 0-6
// are the digits from left to right (D6 is tenths of seconds, D0
// is tens of hours). D7 is AM, PM and the four LEDs for the colons.
// To blink, you write different stuff to P1 and P0 and turn on
// blinking in the config register (bit E to turn on, bit B for speed).
#define MAX_REG_MASK_P0 0x20
#define MAX_REG_MASK_P1 0x40
#define MAX_REG_MASK_BOTH (MAX_REG_MASK_P0 | MAX_REG_MASK_P1)
// When decoding is turned off, this is the bit mapping.
// Segment A is at the top, the rest proceed clockwise around, and
// G is in the middle. DP is the decimal point.
// When decoding is turned on, bits 0-3 are a hex value, 4-6 are ignored,
// and DP is as before.
#define MASK_DP _BV(7)
#define MASK_A _BV(6)
#define MASK_B _BV(5)
#define MASK_C _BV(4)
#define MASK_D _BV(3)
#define MASK_E _BV(2)
#define MASK_F _BV(1)
#define MASK_G _BV(0)
// Digit 7 has the two colons and the AM & PM lights
#ifdef COLONS
#define MASK_COLON_HM (MASK_E | MASK_F)
#define MASK_COLON_MS (MASK_B | MASK_C)
#endif
#define MASK_AM (MASK_A)
#define MASK_PM (MASK_D)
// Digit map
#define DIGIT_10_HR (0)
#define DIGIT_1_HR (1)
#define DIGIT_10_MIN (2)
#define DIGIT_1_MIN (3)
#define DIGIT_10_SEC (4)
#define DIGIT_1_SEC (5)
#define DIGIT_100_MSEC (6)
#define DIGIT_MISC (7)
#define RX_BUF_LEN (96)
#define TX_BUF_LEN (24)
// Note that some versions of the AVR LIBC forgot to
// define the individual PUExn bit numbers.
#ifndef PUEA0
#define PUEA0 0
#define PUEA1 1
#define PUEA2 2
#define PUEA3 3
#define PUEA4 4
#define PUEA5 5
#define PUEA6 6
#define PUEA7 7
#define PUEB0 0
#define PUEB1 1
#define PUEB2 2
#define PUEB3 3
#endif
#ifdef V31
#define PORT_SW PINA
#define SW_0_BIT _BV(PINA0)
#define SW_1_BIT _BV(PINA3)
// DDR_BITS_A doesn't need to be adjusted. The correct bits are already inputs.
// Port B only has the PPS input, so it's zero.
#define DDR_BITS_B (0)
#define PULLUP_BITS_A _BV(PUEA0) | _BV(PUEA3)
#else // !V31
// Port B is the switches and the PPS GPS input
#define PORT_SW PINB
#define DDR_BITS_B (0)
#define SW_0_BIT _BV(PINB0)
#ifdef V3
#define SW_1_BIT _BV(PINB1)
#else // !V3
#define SW_1_BIT _BV(PINB2)
#endif
#ifdef V3
#define PULLUP_BITS_B _BV(PUEB0) | _BV(PUEB1)
#else // !V3
#define PULLUP_BITS_B _BV(PUEB0) | _BV(PUEB2)
#endif
#endif
// These are return values from the DST detector routine.
// DST is not in effect all day
#define DST_NO 0
// DST is in effect all day
#define DST_YES 1
// DST begins at 0200
#define DST_BEGINS 2
// DST ends 0300 - that is, at 0200 pre-correction.
#define DST_ENDS 3
// The possible values for dst_mode
#define DST_OFF 0
#define DST_US 1
#define DST_EU 2
#define DST_AU 3
#define DST_NZ 4
#define DST_MODE_MAX DST_NZ
#ifdef COLONS
#define COLON_OFF 0
#define COLON_ON 1
#define COLON_BLINK 2
#define COLON_STATE_MAX COLON_BLINK
#endif
// EEPROM locations to store the configuration.
#define EE_TIMEZONE ((uint8_t*)0)
#define EE_DST_MODE ((uint8_t*)1)
#define EE_AM_PM ((uint8_t*)2)
#define EE_BRIGHTNESS ((uint8_t*)3)
#ifdef TENTH_DIGIT
#define EE_TENTHS ((uint8_t*)4)
#endif
#ifdef COLONS
#define EE_COLONS ((uint8_t*)5)
#endif
// This is the timer frequency - it's the system clock prescaled by 8
#define F_TICK (F_CPU / 8)
// We want something like 50 ms.
#define DEBOUNCE_TICKS (F_TICK / 20)
// The buttons
#define SELECT 1
#define SET 2
// If we don't get a PPS at least this often, then we've lost it.
// This is F_TICK*1.25 - a quarter second late.
#define LOST_PPS_TICKS (F_TICK + F_TICK / 4)
// For unknown reasons, we sometimes get a first PPS tick that's way, way
// too fast. Rather than have the display look weird, we'll just skip
// showing tenths anytime GPS tells us a tenth of a second is less than
// 50 ms worth of system clock.
#define FAST_PPS_TICKS (F_TICK / 20)
volatile unsigned char disp_buf[8];
volatile unsigned char rx_buf[RX_BUF_LEN];
volatile unsigned char rx_str_len;
volatile unsigned char tx_buf[TX_BUF_LEN];
volatile unsigned int tx_buf_head, tx_buf_tail;
volatile unsigned char nmea_ready;
volatile unsigned long last_pps_tick;
volatile unsigned long tenth_ticks;
volatile unsigned char gps_locked;
volatile unsigned char dst_mode;
volatile unsigned char ampm;
volatile unsigned char menu_pos;
volatile char tz_hour;
volatile unsigned int timer_hibits;
#ifdef TENTH_DIGIT
volatile unsigned char tenth_enable;
volatile unsigned char disp_tenth;
volatile unsigned char tenth_dp;
#endif
#ifdef COLONS
unsigned char colon_state;
#endif
unsigned long debounce_time;
unsigned char button_down;
unsigned char brightness;
unsigned int fw_version_year, utc_ref_year;
unsigned char fw_version_mon, utc_ref_mon;
unsigned char fw_version_day, utc_ref_day;
// Delay, but pet the watchdog while doing it.
static void Delay(unsigned long ms) {
while(ms > 100) {
_delay_ms(100);
wdt_reset();
ms -= 100;
}
_delay_ms(ms);
wdt_reset();
}
void write_reg(const unsigned char addr, const unsigned char val) {
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
#ifndef V3
// We have to make !SS an output for the duration of SPI master mode.
// If it's an input and becomes low, the SPI controller get screwed up.
// Trouble is, it's connected to another device (the GPS module) that's
// actively sending a signal. So to avoid making a short circuit, we
// copy the current input state to the output port and just hope that
// the signal doesn't change for the duration of the SPI transaction.
if (PINA & _BV(PINA7)) {
PORTA |= _BV(PORTA7);
} else {
PORTA &= ~_BV(PORTA7);
}
DDRA |= _BV(DDA7); // Make !SS an output
SPCR = _BV(SPE) | _BV(MSTR); // And turn on SPI
#endif
// Now assert !CS
PORT_MAX &= ~BIT_MAX_CS;
SPDR = addr;
while(!(SPSR & _BV(SPIF))) ;
SPDR = val;
while(!(SPSR & _BV(SPIF))) ;
// And finally, release !CS.
PORT_MAX |= BIT_MAX_CS;
#ifndef V3
SPCR = 0; // Turn off SPI
DDRA &= ~_BV(DDA7); // and revert the !SS pin back to an input.
//PORTA &= ~_BV(PORTA7); // This doesn't really matter. Pull-ups are via PUEx.
#endif
}
}
const unsigned char month_tweak[] PROGMEM = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 };
static inline unsigned char first_sunday(unsigned char m, unsigned int y) {
// first, what's the day-of-week for the first day of whatever month?
// From http://en.wikipedia.org/wiki/Determination_of_the_day_of_the_week
y -= m < 3;
unsigned char month_tweak_val = pgm_read_byte(&(month_tweak[m - 1]));
unsigned char dow = (y + y/4 - y/100 + y/400 + month_tweak_val + 1) % 7;
// If the 1st is a Sunday, then the answer is 1. Otherwise, we count
// up until we find a Sunday.
return (dow == 0)?1:(8 - dow);
}
static inline unsigned char calculateDSTAU(const unsigned char d, const unsigned char m, const unsigned int y) {
// DST is in effect between the first Sunday in October and the first Sunday in April
unsigned char change_day;
switch(m) {
case 1: // November through March
case 2:
case 3:
case 11:
case 12:
return DST_YES;
case 4: // April
change_day = first_sunday(m, y);
if (d < change_day) return DST_YES;
else if (d == change_day) return DST_ENDS;
else return DST_NO;
break;
case 5: // April through September
case 6:
case 7:
case 8:
case 9:
return DST_NO;
case 10: // October
change_day = first_sunday(m, y);
if (d < change_day) return DST_NO;
else if (d == change_day) return DST_BEGINS;
else return DST_YES;
break;
default: // This is impossible, since m can only be between 1 and 12.
return 255;
}
}
static inline unsigned char calculateDSTNZ(const unsigned char d, const unsigned char m, const unsigned int y) {
// DST is in effect between the last Sunday in September and the first Sunday in April
unsigned char change_day;
switch(m) {
case 1: // October through March
case 2:
case 3:
case 10:
case 11:
case 12:
return DST_YES;
case 4: // April
change_day = first_sunday(m, y);
if (d < change_day) return DST_YES;
else if (d == change_day) return DST_ENDS;
else return DST_NO;
break;
case 5: // April through August
case 6:
case 7:
case 8:
return DST_NO;
case 9: // September
change_day = first_sunday(m, y);
while(change_day + 7 <= 30) change_day += 7; // last Sunday
if (d < change_day) return DST_NO;
else if (d == change_day) return DST_BEGINS;
else return DST_YES;
break;
default: // This is impossible, since m can only be between 1 and 12.
return 255;
}
}
static inline unsigned char calculateDSTEU(const unsigned char d, const unsigned char m, const unsigned int y) {
// DST is in effect between the last Sunday in March and the last Sunday in October
unsigned char change_day;
switch(m) {
case 1: // November through February
case 2:
case 11:
case 12:
return DST_NO;
case 3: // March
change_day = first_sunday(m, y);
while(change_day + 7 <= 31) change_day += 7; // last Sunday
if (d < change_day) return DST_NO;
else if (d == change_day) return DST_BEGINS;
else return DST_YES;
break;
case 4: // April through September
case 5:
case 6:
case 7:
case 8:
case 9:
return DST_YES;
case 10: // October
change_day = first_sunday(m, y);
while(change_day + 7 <= 31) change_day += 7; // last Sunday
if (d < change_day) return DST_YES;
else if (d == change_day) return DST_ENDS;
else return DST_NO;
break;
default: // This is impossible, since m can only be between 1 and 12.
return 255;
}
}
static inline unsigned char calculateDSTUS(const unsigned char d, const unsigned char m, const unsigned int y) {
// DST is in effect between the 2nd Sunday in March and the first Sunday in November
// The return values here are that DST is in effect, or it isn't, or it's beginning
// for the year today or it's ending today.
unsigned char change_day;
switch(m) {
case 1: // December through February
case 2:
case 12:
return DST_NO;
case 3: // March
change_day = first_sunday(m, y) + 7; // second Sunday.
if (d < change_day) return DST_NO;
else if (d == change_day) return DST_BEGINS;
else return DST_YES;
break;
case 4: // April through October
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
return DST_YES;
case 11: // November
change_day = first_sunday(m, y);
if (d < change_day) return DST_YES;
else if (d == change_day) return DST_ENDS;
else return DST_NO;
break;
default: // This is impossible, since m can only be between 1 and 12.
return 255;
}
}
static inline unsigned char calculateDST(const unsigned char d, const unsigned char m, const unsigned int y) {
switch(dst_mode) {
case DST_US:
return calculateDSTUS(d, m, y);
case DST_EU:
return calculateDSTEU(d, m, y);
case DST_AU:
return calculateDSTAU(d, m, y);
case DST_NZ:
return calculateDSTNZ(d, m, y);
default: // off - should never happen
return DST_NO;
}
}
static inline void startLeapCheck();
static inline void handle_time(char h, unsigned char m, unsigned char s, unsigned char dst_flags) {
// What we get is the current second. We have to increment it
// to represent the *next* second.
s++;
// Note that this also handles leap-seconds. We wind up pinning to 0
// twice.
if (s >= 60) { s = 0; m++; }
if (m >= 60) { m = 0; h++; }
if (h >= 24) { h = 0; }
// Move to local standard time.
h += tz_hour;
while (h >= 24) h -= 24;
while (h < 0) h += 24;
if (dst_mode != DST_OFF) {
unsigned char dst_offset = 0;
// For Europe, decisions are at 0100. Everywhere else it's 0200.
unsigned char decision_hour = (dst_mode == DST_EU)?1:2;
switch(dst_flags) {
case DST_NO: dst_offset = 0; break; // do nothing
case DST_YES: dst_offset = 1; break; // add one hour
case DST_BEGINS:
dst_offset = (h >= decision_hour)?1:0; // offset becomes 1 at 0200 (0100 EU)
break;
case DST_ENDS:
// The *summer time* hour has to be the decision hour,
// and we haven't yet made 'h' the summer time hour,
// so compare it to one less than the decision hour.
dst_offset = (h >= (decision_hour - 1))?0:1; // offset becomes 0 at 0200 (daylight) (0100 EU)
break;
}
h += dst_offset;
if (h >= 24) h -= 24;
}
// Every hour, check to see if the leap second value in the receiver is out-of-date
unsigned char doLeapCheck = (m == 30 && s == 0);
unsigned char am = 0;
if (ampm) {
// Create AM or PM
if (h == 0) { h = 12; am = 1; }
else if (h < 12) { am = 1; }
else if (h > 12) h -= 12;
}
disp_buf[DIGIT_1_SEC] = (s % 10);
disp_buf[DIGIT_10_SEC] = s / 10;
disp_buf[DIGIT_1_MIN] = (m % 10);
disp_buf[DIGIT_10_MIN] = m / 10;
disp_buf[DIGIT_1_HR] = (h % 10);
disp_buf[DIGIT_10_HR] = h / 10;
disp_buf[DIGIT_100_MSEC] = disp_buf[DIGIT_MISC] = 0;
#ifndef COLONS
// If we don't have colons, add decimal points as separators
disp_buf[DIGIT_1_HR] |= MASK_DP;
disp_buf[DIGIT_1_MIN] |= MASK_DP;
#endif
if (ampm) {
#ifdef NEW_AMPM
disp_buf[DIGIT_MISC] |= am ? MASK_AM : MASK_PM;
#else
// Early hardware used the digit 6 and 7 DPs for AM/PM.
if (am)
disp_buf[DIGIT_MISC] |= MASK_DP;
else
disp_buf[DIGIT_100_MSEC] |= MASK_DP;
#endif
}
#ifdef COLONS
if (colon_state == COLON_ON || ((colon_state == COLON_BLINK) && (s % 2 == 0))) {
disp_buf[DIGIT_MISC] |= MASK_COLON_HM | MASK_COLON_MS;
}
#endif
if (doLeapCheck) startLeapCheck();
}
static inline void tx_char(const unsigned char c);
static inline void write_msg(const unsigned char *msg, const size_t length) {
for(int i = 0; i < length; i++) {
tx_char(msg[i]);
}
}
const unsigned char PROGMEM version_msg[] = { 0xa0, 0xa1, 0x00, 0x02, 0x02, 0x01, 0x03, 0x0d, 0x0a };
static inline void startVersionCheck(void) {
// Ask for the firnware version. We expect a 0x80 in response
unsigned char msg[sizeof(version_msg)];
memcpy_P(msg, version_msg, sizeof(version_msg));
write_msg(msg, sizeof(msg));
}
const unsigned char PROGMEM leap_check_msg[] = { 0xa0, 0xa1, 0x00, 0x02, 0x64, 0x20, 0x44, 0x0d, 0x0a };
static inline void startLeapCheck(void) {
// Ask for the time message. We expect a 0x64-0x8e in response
unsigned char msg[sizeof(leap_check_msg)];
memcpy_P(msg, leap_check_msg, sizeof(leap_check_msg));
write_msg(msg, sizeof(msg));
}
const unsigned char PROGMEM leap_update_msg[] = { 0xa0, 0xa1, 0x00, 0x04, 0x64, 0x1f, 0x00, 0x01, 0x7a, 0x0d, 0x0a };
static inline void updateLeapDefault(const unsigned char leap_offset) {
// This is a set leap-second default message. It will write the given
// offset to flash.
unsigned char msg[sizeof(leap_update_msg)];
memcpy_P(msg, leap_update_msg, sizeof(leap_update_msg));
msg[6] = leap_offset;
msg[8] ^= leap_offset; // fix the checksum
write_msg(msg, sizeof(msg));
}
const unsigned char PROGMEM get_utc_ref_msg[] = { 0xa0, 0xa1, 0x00, 0x02, 0x64, 0x16, 0x72, 0x0d, 0x0a };
static inline void startUTCReferenceFetch() {
// This is a request for UTC reference date message. We expect a 0x64-0x8a in response
unsigned char msg[sizeof(get_utc_ref_msg)];
memcpy_P(msg, get_utc_ref_msg, sizeof(get_utc_ref_msg));
write_msg(msg, sizeof(msg));
}
const unsigned char PROGMEM utc_ref_msg[] = { 0xa0, 0xa1, 0x00, 0x08, 0x64, 0x15, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01, 0x71, 0x0d, 0x0a };
static inline void updateUTCReference(const unsigned int y, const unsigned char mon, const unsigned char d) {
// This sets the UTC reference date, which controls the boundaries of the GPS week window
unsigned char msg[sizeof(utc_ref_msg)];
memcpy_P(msg, utc_ref_msg, sizeof(utc_ref_msg));
msg[7] = (unsigned char)(y >> 8);
msg[8] = (unsigned char)y;
msg[9] = mon;
msg[10] = d;
for(int i = 7; i <= 10; i++) msg[12] ^= msg[i]; // fix checksum
write_msg(msg, sizeof(msg));
}
static const char *skip_commas(const char *ptr, const int num) {
for(int i = 0; i < num; i++) {
ptr = strchr(ptr, ',');
if (ptr == NULL) return NULL; // not enough commas
ptr++; // skip over it
}
return ptr;
}
const char hexes[] PROGMEM = "0123456789abcdef";
static unsigned char hexChar(unsigned char c) {
if (c >= 'A' && c <= 'F') c += ('a' - 'A'); // make lower case
const char* outP = strchr_P(hexes, c);
if (outP == NULL) return 0;
return (unsigned char)(outP - hexes);
}
static inline void handleGPS(unsigned char binaryOnly) {
unsigned int str_len = rx_str_len; // rx_str_len is where the \0 was written.
if (str_len >= 3 && rx_buf[0] == 0xa0 && rx_buf[1] == 0xa1) { // binary protocol message
unsigned int payloadLength = (((unsigned int)rx_buf[2]) << 8) | rx_buf[3];
if (str_len != payloadLength + 7) return; // the A0, A1 bytes, length and checksum are added
unsigned int checksum = 0;
for(int i = 0; i < payloadLength; i++) checksum ^= rx_buf[i + 4];
if (checksum != rx_buf[payloadLength + 4]) return; // checksum mismatch
if (rx_buf[4] == 0x80) {
fw_version_year = rx_buf[12 + 3];
fw_version_mon = rx_buf[13 + 3];
fw_version_day = rx_buf[14 + 3];
} else if (rx_buf[4] == 0x64 && rx_buf[5] == 0x8a) {
utc_ref_year = (rx_buf[3 + 4] << 8) | rx_buf[3 + 5];
utc_ref_mon = rx_buf[3 + 6];
utc_ref_day = rx_buf[3 + 7];
} else if (rx_buf[4] == 0x64 && rx_buf[5] == 0x8e) {
if (!(rx_buf[15 + 3] & (1 << 2))) return; // GPS leap seconds invalid
if (rx_buf[13 + 3] == rx_buf[14 + 3]) return; // Current and default agree
updateLeapDefault(rx_buf[14 + 3]);
} else {
return; // unknown binary protocol message
}
}
if (binaryOnly) return; // we're not handling text sentences.
if (str_len < 9) return; // No sentence is shorter than $GPGGA*xx
// First, check the checksum of the sentence
unsigned char checksum = 0;
int i;
for(i = 1; i < str_len; i++) {
if (rx_buf[i] == '*') break;
checksum ^= rx_buf[i];
}
if (i > str_len - 3) {
return; // there has to be room for the "*" and checksum.
}
i++; // skip the *
unsigned char sent_checksum = (hexChar(rx_buf[i]) << 4) | hexChar(rx_buf[i + 1]);
if (sent_checksum != checksum) {
return; // bad checksum.
}
const char *ptr = (char *)rx_buf;
if (!strncmp_P(ptr, PSTR("$GPRMC"), 6)) {
// $GPRMC,172313.000,A,xxxx.xxxx,N,xxxxx.xxxx,W,0.01,180.80,260516,,,D*74\x0d\x0a
ptr = skip_commas(ptr, 1);
if (ptr == NULL) return; // not enough commas
char h = (ptr[0] - '0') * 10 + (ptr[1] - '0');
unsigned char min = (ptr[2] - '0') * 10 + (ptr[3] - '0');
unsigned char s = (ptr[4] - '0') * 10 + (ptr[5] - '0');
ptr = skip_commas(ptr, 1);
if (ptr == NULL) return; // not enough commas
gps_locked = *ptr == 'A'; // A = AOK
ptr = skip_commas(ptr, 7);
if (ptr == NULL) return; // not enough commas
unsigned char d = (ptr[0] - '0') * 10 + (ptr[1] - '0');
unsigned char mon = (ptr[2] - '0') * 10 + (ptr[3] - '0');
unsigned int y = (ptr[4] - '0') * 10 + (ptr[5] - '0');
// We must turn the two digit year into the actual A.D. year number.
// As time goes forward, we can keep a record of how far time has gotten,
// and assume that time will always go forwards. If we see a date ostensibly
// in the past, then it "must" mean that we've actually wrapped and need to
// add 100 years. We keep this "reference" date in sync with the GPS receiver,
// as it uses the reference date to control the GPS week rollover window.
y += 2000;
while (y < utc_ref_year) y += 100; // If it's in the "past," assume time wrapped on us.
if (utc_ref_year != 0 && y != utc_ref_year) {
// Once a year, we should update the refence date in the receiver. If we're running on New Years,
// then that's probably when it will happen, but anytime is really ok. We just don't want to do
// it a lot for fear of burning the flash out in the GPS receiver.
updateUTCReference(y, mon, d);
utc_ref_year = y;
utc_ref_mon = mon;
utc_ref_day = d;
}
// The problem is that our D/M/Y is UTC, but DST decisions are made in the local
// timezone. We can adjust the day against standard time midnight, and
// that will be good enough. Don't worry that this can result in d being either 0
// or past the last day of the month. Those will still be more or less than the "decision day"
// for DST, which is all that really matters.
if (h + tz_hour < 0) d--;
if (h + tz_hour > 23) d++;
unsigned char dst_flags = calculateDST(d, mon, y);
handle_time(h, min, s, dst_flags);
}
}
ISR(USART0_RX_vect) {
unsigned char rx_char = UDR0;
if (nmea_ready) return; // ignore serial until current buffer handled
if (rx_str_len == 0 && !(rx_char == '$' || rx_char == 0xa0)) return; // wait for a "$" or A0 to start the line.
rx_buf[rx_str_len] = rx_char;
if (++rx_str_len == RX_BUF_LEN) {
// The string is too long. Start over.
rx_str_len = 0;
}
// If it's an ASCII message, then it's ended with a CRLF.
// If it's a binary message, then it's ended when it's the correct length
if ( (rx_buf[0] == '$' && (rx_char == 0x0d || rx_char == 0x0a)) ||
(rx_buf[0] == 0xa0 && rx_str_len >= 4 && rx_str_len >= ((rx_buf[2] << 8) + rx_buf[3] + 7)) ) {
rx_buf[rx_str_len] = 0; // null terminate
nmea_ready = 1; // Mark it as ready
return;
}
}
ISR(USART0_UDRE_vect) {
if (tx_buf_head == tx_buf_tail) {
// the transmit queue is empty.
UCSR0B &= ~_BV(UDRIE0); // disable the TX interrupt
return;
}
UDR0 = tx_buf[tx_buf_tail];
if (++tx_buf_tail == TX_BUF_LEN) tx_buf_tail = 0; // point to the next char
}
// If the TX buffer fills up, then this method will block, which should be avoided.
static inline void tx_char(const unsigned char c) {
int buf_in_use;
do {
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
buf_in_use = tx_buf_head - tx_buf_tail;
}
if (buf_in_use < 0) buf_in_use += TX_BUF_LEN;
wdt_reset(); // we might be waiting a while.
} while (buf_in_use >= TX_BUF_LEN - 2) ; // wait for room in the transmit buffer
tx_buf[tx_buf_head] = c;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
// this needs to be atomic, because an intermediate state is tx_buf_head
// pointing *beyond* the end of the buffer.
if (++tx_buf_head == TX_BUF_LEN) tx_buf_head = 0; // point to the next free spot in the tx buffer
}
UCSR0B |= _BV(UDRIE0); // enable the TX interrupt. If it was disabled, then it will trigger one now.
}
static void write_no_sig() {
tenth_ticks = 0;
// Clear out the digit data
write_reg(MAX_REG_CONFIG, MAX_REG_CONFIG_R | MAX_REG_CONFIG_B | MAX_REG_CONFIG_S | MAX_REG_CONFIG_E);
write_reg(MAX_REG_DEC_MODE, 0);
write_reg(MAX_REG_MASK_BOTH | 0, MASK_C | MASK_E | MASK_G); // n
write_reg(MAX_REG_MASK_BOTH | 1, MASK_C | MASK_D | MASK_E | MASK_G); // o
write_reg(MAX_REG_MASK_BOTH | 3, MASK_A | MASK_C | MASK_D | MASK_E | MASK_F | MASK_G); // G
write_reg(MAX_REG_MASK_BOTH | 4, MASK_A | MASK_B | MASK_E | MASK_F | MASK_G); // P
write_reg(MAX_REG_MASK_BOTH | 5, MASK_A | MASK_C | MASK_D | MASK_F | MASK_G); // S
}
static inline unsigned long timer_value() __attribute__ ((always_inline));
static inline unsigned long timer_value() {
unsigned long now;
ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
// We have to be careful. It's possible that we capture TCNTn at the same
// time as an overflow. If that happens, it means that the hibits value
// is 1 too low. We can detect this by checking if the low bits are
// "close" to zero and if the overflow interrupt is pending. If that's
// true, then we can compensate locally for the missing interrupt (and
// it will happen when we return anyway). If the low bits are high,
// then the interrupt is pending because it came (shortly) after we sampled, so
// we don't compensate. "close" can simply be testing the MSB for 0.
#ifdef V3
now = (((unsigned long)timer_hibits) << 16) | TCNT2;
if ((TIFR2 & _BV(TOV2)) && !(now & 0x8000)) now += 0x10000L;
#else
now = (((unsigned long)timer_hibits) << 16) | TCNT1;
if ((TIFR1 & _BV(TOV1)) && !(now & 0x8000)) now += 0x10000L;
#endif
}
return now;
}
#ifdef V3
ISR(TIMER2_OVF_vect) {
#else
ISR(TIMER1_OVF_vect) {
#endif
timer_hibits++;
}
#ifdef V2
#ifdef V3
ISR(TIMER2_CAPT_vect) {
unsigned long this_tick = (((unsigned long)timer_hibits) << 16) | ICR2;
#else
ISR(TIMER1_CAPT_vect) {
unsigned long this_tick = (((unsigned long)timer_hibits) << 16) | ICR1;
#endif
#else
ISR(INT0_vect) {
unsigned long this_tick = (((unsigned long)timer_hibits) << 16) | TCNT1;
#endif
#ifdef V3
if ((TIFR2 & _BV(TOV2)) && !(this_tick & 0x8000)) this_tick += 0x10000L;
#else
if ((TIFR1 & _BV(TOV1)) && !(this_tick & 0x8000)) this_tick += 0x10000L;
#endif
#ifdef TENTH_DIGIT
if (menu_pos == 0 && tenth_enable && last_pps_tick != 0) {
tenth_ticks = (this_tick - last_pps_tick) / 10;
// For unknown reasons we seemingly sometimes get spurious
// PPS interrupts. If the calculus leads us to believe a
// a tenth of a second is less than 50 ms worth of system clock,
// then it's not right - just skip it.
if (tenth_ticks < FAST_PPS_TICKS) tenth_ticks = 0;
} else {
tenth_ticks = 0;
}
#endif
last_pps_tick = this_tick;
if (last_pps_tick == 0) last_pps_tick++; // it can never be zero
if (menu_pos) return;
if (!gps_locked) {
write_no_sig();
return;
}
unsigned char decode_mask = (unsigned char)~_BV(DIGIT_MISC); // assume decoding for all digits
// If we are doing 12 hour display and if the 10 hours digit is 0, then blank it instead.
// Its value will be zero, so simply disabling the hex decode will result in no segments.
if (ampm && disp_buf[DIGIT_10_HR] == 0) {
decode_mask &= ~_BV(DIGIT_10_HR); // No decode for tens-of-hours digit
}
#ifdef TENTH_DIGIT
// If we're not going to show the tenths...
if (tenth_ticks == 0) {
decode_mask &= ~_BV(DIGIT_100_MSEC); // No decode for tenth digit
} else {
disp_buf[DIGIT_1_SEC] |= MASK_DP; // add a decimal point on seconds digit
}
disp_tenth = 0; // right now, 0 is showing.
// Watch out, there's an old bug lurking here. disp_buf[] gets
// updated with data for the *next* second early on during *this*
// second. If the tenth DP is ever used for anything time related,
// (it used to be used for PM), then it will wind up changing *early*
// if you're not careful.
tenth_dp = (disp_buf[DIGIT_100_MSEC] & MASK_DP) != 0;
#else
decode_mask &= ~_BV(DIGIT_100_MSEC); // No decode for tenth digit
#endif
write_reg(MAX_REG_DEC_MODE, decode_mask);
// Copy the display buffer data into the display, but do the least
// significant digits first, for great justice.
for(int i = sizeof(disp_buf) - 1; i >= 0; i--) {
write_reg(MAX_REG_MASK_BOTH | i, disp_buf[i]);
}
}
static unsigned char check_buttons() {
unsigned long now = timer_value();
if (debounce_time != 0 && now - debounce_time < DEBOUNCE_TICKS) {
// We don't pay any attention to the buttons during debounce time.
return 0;
} else {
debounce_time = 0; // debounce is over
}
unsigned char status = PORT_SW & (SW_0_BIT | SW_1_BIT);
status ^= (SW_0_BIT | SW_1_BIT); // invert the buttons - 0 means down.
if (!((button_down == 0) ^ (status == 0))) return 0; // either no button is down, or a button is still down
// Something *changed*, which means we must now start a debounce interval.
debounce_time = now;
if (!debounce_time) debounce_time++; // it's not allowed to be zero
if (!button_down && status) {
button_down = 1; // a button has been pushed
return (status & SW_1_BIT)?SELECT:SET;
}
if (button_down && !status) {
button_down = 0; // a button has been released
return 0;
}
__builtin_unreachable(); // we'll never get here.
}
static void menu_render() {
// blank the display
write_reg(MAX_REG_DEC_MODE, 0); // no decoding
write_reg(MAX_REG_CONFIG, MAX_REG_CONFIG_R | MAX_REG_CONFIG_B | MAX_REG_CONFIG_S | MAX_REG_CONFIG_E);
switch(menu_pos) {
case 0:
// we're returning to time mode. Either leave it blank or indicate no signal.
if (!gps_locked)
write_no_sig();
tenth_ticks = 0;
break;
case 1: // zone
write_reg(MAX_REG_DEC_MODE, 0x30); // decoding for last two digits only
write_reg(MAX_REG_MASK_BOTH | 0, MASK_D | MASK_E | MASK_F | MASK_G); // t
write_reg(MAX_REG_MASK_BOTH | 1, MASK_C | MASK_E | MASK_F | MASK_G); // h
if (tz_hour < 0) {
write_reg(MAX_REG_MASK_BOTH | 3, MASK_G); // -
}
write_reg(MAX_REG_MASK_BOTH | 4, abs(tz_hour) / 10);
write_reg(MAX_REG_MASK_BOTH | 5, abs(tz_hour) % 10);
break;
case 2: // DST on/off
write_reg(MAX_REG_DEC_MODE, 0); // no decoding
write_reg(MAX_REG_MASK_BOTH | 0, MASK_B | MASK_C | MASK_D | MASK_E | MASK_G); // d
write_reg(MAX_REG_MASK_BOTH | 1, MASK_A | MASK_C | MASK_D | MASK_F | MASK_G); // S
switch(dst_mode) {
case DST_OFF:
write_reg(MAX_REG_MASK_BOTH | 3, MASK_C | MASK_D | MASK_E | MASK_G); // o
write_reg(MAX_REG_MASK_BOTH | 4, MASK_A | MASK_E | MASK_F | MASK_G); // F
write_reg(MAX_REG_MASK_BOTH | 5, MASK_A | MASK_E | MASK_F | MASK_G); // F
break;
case DST_EU:
write_reg(MAX_REG_MASK_BOTH | 3, MASK_A | MASK_D | MASK_E | MASK_F | MASK_G); // E
write_reg(MAX_REG_MASK_BOTH | 4, MASK_B | MASK_C | MASK_D | MASK_E | MASK_F); // U
break;
case DST_US:
write_reg(MAX_REG_MASK_BOTH | 3, MASK_B | MASK_C | MASK_D | MASK_E | MASK_F); // U
write_reg(MAX_REG_MASK_BOTH | 4, MASK_A | MASK_C | MASK_D | MASK_F | MASK_G); // S
break;
case DST_AU:
write_reg(MAX_REG_MASK_BOTH | 3, MASK_A | MASK_B | MASK_C | MASK_E | MASK_F | MASK_G); // A
write_reg(MAX_REG_MASK_BOTH | 4, MASK_B | MASK_C | MASK_D | MASK_E | MASK_F); // U
break;
case DST_NZ:
write_reg(MAX_REG_MASK_BOTH | 3, MASK_C | MASK_E | MASK_G); // n
write_reg(MAX_REG_MASK_BOTH | 4, MASK_A | MASK_B | MASK_D | MASK_E | MASK_G); // Z
break;
}
break;
case 3: // 12/24 hour
write_reg(MAX_REG_DEC_MODE, 0x6); // decoding for first two digits only (skipping one)
write_reg(MAX_REG_MASK_BOTH | 1, ampm?1:2);
write_reg(MAX_REG_MASK_BOTH | 2, ampm?2:4);
write_reg(MAX_REG_MASK_BOTH | 4, MASK_C | MASK_E | MASK_F | MASK_G); // h
write_reg(MAX_REG_MASK_BOTH | 5, MASK_E | MASK_G); // r
break;
#ifdef TENTH_DIGIT
case 4: // tenths enabled
write_reg(MAX_REG_DEC_MODE, 3); // decode only first two digits